SQL Server将多行作为多个列

时间:2015-01-30 07:16:20

标签: sql-server sql-server-2008-r2 pivot common-table-expression

我的测试数据如下:

表中还有一个uniqueidentifier列。

**Month       Cost**

Jan         1000
Feb         1500
May         1200

我期待的结果是格式

Jan     Feb     Mar     Apr     May 
1000    1500    NULL    NULL    1200

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

2 个答案:

答案 0 :(得分:1)

如果月份总是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

运行它

答案 1 :(得分:0)

您可以将行转换为列

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