SQl Server 2005:列到列 - 如何应对这一挑战?

时间:2010-07-29 11:40:17

标签: sql sql-server sql-server-2005

请告诉我,如何转换以下数据,

[id]  cost1  cost2    year 
   1      5     10    2010 
   1      4     15    2011 
   2     10     10    2010

采用此格式['年'到列标题的行'

id [cost1-2010] [cost2-2010] [cost1-2011] [cost2-2011] 
 1           5           10            4           15 
 2          10           10            0            0

4 个答案:

答案 0 :(得分:3)

答案 1 :(得分:1)

尝试这样的事情:

DECLARE @YourTable table (id int, cost1 int, cost2 int, year int)
INSERT @YourTable VALUES (1,5,10,2010)
INSERT @YourTable VALUES (1,4,15,2011)
INSERT @YourTable VALUES (2,10,10,2010)

SELECT
    id
        ,SUM(CASE WHEN year=2010 THEN cost1 else 0 END) AS "Cost1-2010"
        ,SUM(CASE WHEN year=2010 THEN cost2 else 0 END) AS "Cost2-2010"
        ,SUM(CASE WHEN year=2011 THEN cost1 else 0 END) AS "Cost1-2011"
        ,SUM(CASE WHEN year=2011 THEN cost2 else 0 END) AS "Cost2-2010"
    FROM @YourTable
    GROUP BY id

输出

id          Cost1-2010  Cost2-2010  Cost1-2011  Cost2-2010
----------- ----------- ----------- ----------- -----------
1           5           10          4           15
2           10          10          0           0

(2 row(s) affected)

答案 2 :(得分:0)

如果你想根据数据动态地做这件事,那么比仅仅使用PIVOT更困难。对于PIVOT或条件求和技术

[2010Values] = ( SUM(Case when year = 2010 then FieldValue Else 0 End)

您必须提前知道列名。

如果您希望根据收到的数据动态设置列名,那么您将不得不采用可能变得丑陋的动态SQL路由。

答案 3 :(得分:0)

查看有关this post的讨论。那应该是你拨打的。