SQL Multiple WHERE分配一个新的表列

时间:2013-06-27 15:02:19

标签: sql select sum where multiple-instances

由于我缺乏语言经验,我遇到了一些问题,希望得到你们的帮助......

我希望代码返回表格,如下例所示:

T01 --  T02 -- T03
23,00  32,00  43,00

所以,继承我的代码:

SELECT
SUM([TOTAL $]) AS T01
FROM PFIN_base
WHERE [COORD] = 'alfa'
UNION
SELECT
SUM([TOTAL $]) AS T02
FROM PFIN_base
WHERE [COORD] = 'beta'
UNION
SELECT 
SUM([TOTAL $]) AS T03
FROM PFIN_base
WHERE [COORD] = 'gama'

此代码返回以下结果:

T01
23,00
32,00
43,00

我如何获得理想的结果? 谢谢!

1 个答案:

答案 0 :(得分:1)

您想要条件聚合:

select sum(case when coord = 'alfa' then [TOTAL $] end) as T01,
       sum(case when coord = 'beta' then [TOTAL $] end) as T02,
       sum(case when coord = 'gamma' then [TOTAL $] end) as T03
from PFin_base