Sql 根据年数添加更多列
使用SQLServer2008 所以我有一个查询表,最后看起来像这样 例如: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
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的可能重复项