Efficiently convert rows to columns in sql server(在sql server中高效地将行转换为列)
问题描述
我正在寻找一种有效的方法在SQL Server中将行转换为列,听说PIVOT不是很快,我需要处理大量记录.
I'm looking for an efficient way to convert rows to columns in SQL server, I heard that PIVOT is not very fast, and I need to deal with lot of records.
这是我的例子:
这是我的结果:
如何构建结果?
推荐答案
有多种方法可以将数据从多行转换为列.
There are several ways that you can transform data from multiple rows into columns.
在 SQL Server 中,您可以使用 PIVOT
函数将数据从行转换为列:
In SQL Server you can use the PIVOT
function to transform the data from rows to columns:
参见演示.
如果您想转置未知数量的columnnames
,那么您可以使用动态SQL:
If you have an unknown number of columnnames
that you want to transpose, then you can use dynamic SQL:
参见演示.
如果不想使用PIVOT
函数,那么可以使用带有CASE
表达式的聚合函数:
If you do not want to use the PIVOT
function, then you can use an aggregate function with a CASE
expression:
参见演示.
这也可以使用多个连接来完成,但您需要一些列来关联示例数据中没有的每一行.但基本语法是:
This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:
这篇关于在sql server中高效地将行转换为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!