我有一个查询,我有一个SQL数据库。我的数据看起来像这样
Select ROW_NUMBER() OVER (PARTITION BY m.[MKEY] ORDER BY es.[FDATE]) as 'Row', FDATE
PIVOT(
SUM(s.[EARNINGS])
FOR s.[row] IN ([1], [2], [3], [4] ))AS i
Person | FDATE| 1 | 2 | 3 | 4
Sam Smith| 2001 | 200.00 | Null | Null | Null
Sam Smith| 2002 | Null | 400.00| Null | Null
Sam Smith| 2003 | Null | Null | 500.00| Null
我希望像这样
Person | FDATE| 1 |FDATE| 2 |FDATE| 3 |FDATE| 4
Sam Smith | 2001 | 200.00 | 2002 |400.00| 2003| 500.00|NULL| NULL
实现这一目标的最佳方法是什么?任何帮助将不胜感激。
答案 0 :(得分:1)
试试这个:
select
Person
,max(case when coalesce(FDATE,0)=2001 then FDATE else 0 end) as FDATE_1
,sum(case when coalesce(FDATE,0)=2001 then Earnings else 0 end) as [1]
,max(case when coalesce(FDATE,0)=2002 then FDATE else 0 end) as FDATE_2
,sum(case when coalesce(FDATE,0)=2002 then Earnings else 0 end) as [2]
,max(case when coalesce(FDATE,0)=2003 then FDATE else 0 end) as FDATE_3
,sum(case when coalesce(FDATE,0)=2003 then Earnings else 0 end) as [3]
,max(case when coalesce(FDATE,0)=2004 then FDATE else 0 end) as FDATE_4
,sum(case when coalesce(FDATE,0)=2004 then Earnings else 0 end) as [4]
from <table>
group by
Person
请注意,您在SELECT子句中实际要求的列永远不会出现在结果中。