SQL 将多行作为多列服务器

SQL server multiple rows as multiple columns

我的测试数据如下:

table 中也有一个 uniqueidentifier 列。

**Month       Cost**

Jan         1000
Feb         1500
May         1200

我期待的结果是格式

Jan     Feb     Mar     Apr     May 
1000    1500    NULL    NULL    1200

Pivot 或 CTE 或普通查询的任何方法都可以。

如果月份总是 12,您可以轻松使用数据透视表(未测试):

SELECT 
   P.[Jan],P.[Feb],P.[Mar],P.[Apr] 
FROM 
   TABLE
PIVOT 
   (MAX (Cost) for [Month] in ([Jan],[Feb],[Mar],[Apr])) AS P

如果您需要创建动态代码,您必须生成 sql 代码,然后 运行 使用 exec

生成代码

您可以将行转换为列

SELECT
    MIN(CASE WHEN [MONTH]='JAN' THEN Cost END) AS JAN,
    MIN(CASE WHEN [MONTH]='Feb' THEN Cost END) AS Feb,
    MIN(CASE WHEN [MONTH]='MAR' THEN Cost END) AS MAR,
    MIN(CASE WHEN [MONTH]='APR' THEN Cost END) AS APR,
    MIN(CASE WHEN [MONTH]='MAY' THEN Cost END) AS MAY,
    MIN(CASE WHEN [MONTH]='JUN' THEN Cost END) AS JUNE,
    MIN(CASE WHEN [MONTH]='JUL' THEN Cost END) AS JUL,
    MIN(CASE WHEN [MONTH]='AUG' THEN Cost END) AS AUG,
    MIN(CASE WHEN [MONTH]='SEP' THEN Cost END) AS SEP,
    MIN(CASE WHEN [MONTH]='OCT' THEN Cost END) AS OCT,
    MIN(CASE WHEN [MONTH]='NOV' THEN Cost END) AS NOV,
    MIN(CASE WHEN [MONTH]='DEC' THEN Cost END) AS DEC
    FROM YOURTABLE

如果你想要值的总和,你可以将 MIN 更改为 SUM