sqlserver行转列
在SQL Server中,可以使用PIVOT操作将行转换为列。PIVOT操作需要使用聚合函数和GROUP BY子句来指定如何对数据进行汇总。
以下是一个示例,演示如何将行转换为列:
假设有一个名为sales的表,包含以下数据:
| Salesperson | Product | Qty | |-------------|---------|-----| | John | Apple | 5 | | John | Orange | 3 | | Mary | Apple | 2 | | Mary | Banana | 4 |
要将上述数据按销售人员(Salesperson)分组,并将产品(Product)作为列进行汇总,可以使用以下查询:
SELECT Salesperson, [Apple], [Orange], [Banana]
FROM
(
SELECT Salesperson, Product, Qty
FROM sales
) AS SourceTable
PIVOT
(
SUM(Qty)
FOR Product IN ([Apple], [Orange], [Banana])
) AS PivotTable;
上述查询将返回以下结果:
| Salesperson | Apple | Orange | Banana | |-------------|-------|--------|--------| | John | 5 | 3 | NULL | | Mary | 2 | NULL | 4 |
在上述查询中,子查询(SELECT Salesperson, Product, Qty FROM sales)用于选择需要进行行转列的数据。
PIVOT操作使用了SUM(Qty)作为聚合函数,并使用FOR Product IN ([Apple], [Orange], [Banana])指定了要在结果中显示的产品列。
最后,使用别名PivotTable将结果表进行命名。
原文地址: https://www.cveoy.top/t/topic/i51u 著作权归作者所有。请勿转载和采集!