我正在运行SQL Server 2014,我对视图表运行了以下Pivot查询。
(
SELECT [ResID], [F&B], [LEISURE], [SPA]
FROM ( SELECT * FROM [EXTRASEXPENDITURE]
)m
PIVOT (SUM([FOC_NETAMOUNT])
FOR [CATEGORY] IN ([F&B], [LEISURE], [SPA]
))AS PVTTABLE)
ORDER BY [ResID] ASC
当前输出的摘录如下所示:
ResID F&B LEISURE SPA
1024 210.00 0 0
1024 0 125.00 0
1136 0 500.00 0
1136 0 0 325.00
我希望我的输出类似于下表(在ResID级别完成分组):
ResID F&B LEISURE SPA
1024 210.00 125.00 0
1136 0 500.00 325.00
我应该在我的数据透视查询中更正以实现上述结果?
附加说明:
' EXTRASEXPENDITURE'查看表显示如下信息:
ResID FOC_Date Category FOC_NetAmount
1136 2015-10-03 SPA 325.00
1136 2015-10-12 LEISURE 500.00
1136 ..........
答案 0 :(得分:3)
从Pivot
源查询中删除不需要的列,它应该是这样的
SELECT [ResID],
[F&B],
[LEISURE],
[SPA]
FROM (SELECT ResID,
Category,
FOC_NetAmount
FROM Yourtable) a
PIVOT (Sum([FOC_NETAMOUNT])
FOR [CATEGORY] IN ([F&B],
[LEISURE],
[SPA] )) PVTTABLE
ORDER BY [ResID] ASC
答案 1 :(得分:1)
试试这个:
SELECT [ResID],
COALESCE([F&B], 0) AS [F&B],
COALESCE([LEISURE], 0) AS [LEISURE],
COALESCE([SPA], 0) AS [SPA]
FROM (
SELECT [ResID], [Category], [FOC_NetAmount]
FROM [EXTRASEXPENDITURE]) AS src
PIVOT (
SUM([FOC_NETAMOUNT])
FOR [CATEGORY] IN ([F&B], [LEISURE], [SPA]))AS PVTTABLE
ORDER BY [ResID] ASC