【问题标题】:adding more Columns based on number of years根据年数添加更多列
【发布时间】:2013-07-29 20:22:03
【问题描述】:

使用 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

基本上为它返回的每个新年添加一行新的列

【问题讨论】:

标签: sql sql-server-2008 pivot crosstab


【解决方案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

【讨论】:

    猜你喜欢
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多