在T-SQL数据透视查询中需要更改什么才能实现此特定输出?

时间:2016-02-23 07:54:07

标签: sql sql-server tsql pivot

我正在运行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 ..........

2 个答案:

答案 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