在SQL查询中使用SUM和过滤器

时间:2015-02-27 09:21:57

标签: sql-server sum

我正在使用SQL Server 2014,我在查询时遇到了困难。目前我的查询如下:

SELECT  b.FOH_PMSCONFNUM,
        a.FOC_ACCOUNT,
        a.FOC_TCODE,
        a.[Net Amount]

FROM P5FOLIOHEADER b

LEFT JOIN
(SELECT 
        FOC_ACCOUNT, 
        FOC_TCODE, 
        SUM (FOC_NETAMOUNT) AS 'NetAmount'

FROM P5FOLIOCHARGE 

GROUP BY FOC_ACCOUNT,FOC_TCODE) a ON a.FOC_ACCOUNT = b.FOH_ACCOUNT

输出如下:

 FOH_PMSCONFNUM   FOC_ACCOUNT  FOC_TCODE  NetAmount
    1216            52          ROOM       2500
    1216            52          ROOM       2500
    1216            52          ROOM       2500
    1216            52          DRINKS      900
    1216            52          DRINKS      600
    1301            75          ROOM       1800
    1301            75          ROOM       1800
    1653            90          ROOM       3000
    1653            90          TELEX       150

我需要输出如下:

FOH_PMSCONFNUM   FOC_ACCOUNT  NetAmount(Room)  NetAmount(Drinks)  NetAmount(Telex)
    1216              52           7500             1500             0
    1301              75           3600               0              0
    1653              90           3000               0            150   

有没有办法在不使用PIVOT语法的情况下编写此查询?我需要最终将此查询附加到另一个查询。

理想情况下,我正在寻找一个查询,我可以在现有查询中修改此部分:SUM(FOC_NETAMOUNT)AS'NetAmount'并使其成为这样的:

SUM (FOC_NETAMOUNT) AS 'NetAmount(Room)' WHERE FOC_tcode ='ROOM'
SUM (FOC_NETAMOUNT) AS 'NetAmount(Drinks)' WHERE FOC_tcode ='DRINKS'
SUM (FOC_NETAMOUNT) AS 'NetAmount(Telex)' WHERE FOC_tcode ='TELEX'

我只是因为如何在SQL中编写逻辑而陷入困境。

1 个答案:

答案 0 :(得分:0)

您可以在case中使用sum表达式来过滤掉值:

select
  b.FOH_PMSCONFNUM,
  a.FOC_ACCOUNT,
  a.FOC_TCODE,
  sum(case a.FOC_TCODE when 'ROOM' then a.[Net Amount] else 0 end) as 'NetAmount(Room)',
  sum(case a.FOC_TCODE when 'DRINKS' then a.[Net Amount] else 0 end) as 'NetAmount(Drinks)',
  sum(case a.FOC_TCODE when 'TELEX' then a.[Net Amount] else 0 end) as 'NetAmount(Telex)',
from
  P5FOLIOHEADER b
  left join P5FOLIOCHARGE a on a.FOC_ACCOUNT = b.FOH_ACCOUNT
group by
  a.FOC_ACCOUNT