根据年数添加更多列

时间:2013-07-29 21:13:36

标签: sql sql-server-2008 pivot crosstab

使用Sql server 2008 所以我有一个查询表,最后看起来像这样

示例:

month    Year    data
1        2012     123
...      2012     123
12       2012     123
1        2013     123
...      2013     123
12       2013     123

有没有办法对它进行选择,以便它会像这样出现

month    Year    data    month    Year    data
1        2012     123      1      2013     123
...      2012     123      ...    2013     123
12       2012     123      12     2013     123

基本上为每个新年添加一列新的

1 个答案:

答案 0 :(得分:1)

C#或PHP或Python中,客户端更容易。但它可以在SQL中完成:

select  month as Month2012
,       2012 as Year2012
,       max(case when year = 2012 then data end) as Data2012
,       month as Month2013
,       2013 as Year2013
,       max(case when year = 2013 then data end) as Data2013
,       month as Month2014
,       2014 as Year2014
,       max(case when year = 2014 then data end) as Data2014
,       ...
from    YourTable
group by
        month