Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 根据年数添加更多列_Sql_Sql Server 2008_Pivot_Crosstab - Fatal编程技术网

Sql 根据年数添加更多列

Sql 根据年数添加更多列,sql,sql-server-2008,pivot,crosstab,Sql,Sql Server 2008,Pivot,Crosstab,使用SQLServer2008 所以我有一个查询表,最后看起来像这样 例如: month Year data 1 2012 123 ... 2012 123 12 2012 123 1 2013 123 ... 2013 123 12 2013 123 有没有一种方法可以对它进行选择,这样它就会变成这样 month Year data month

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

例如:

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

基本上,它会在每一年返回一行新的列,这在客户端(在
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

您使用的是哪种数据库管理系统?(PostgreSQL?MySQL?SQL Server?Oracle?)。sql server 2008的可能重复项