SQL如何获取字段总和为特定值并使其成为列标题?

时间:2018-05-09 01:12:06

标签: sql

例如:我有一个这样的表:

    ------------------------------------
    ID | Name | Color | Account | Amt  |
    1  | Mark | Red   | 001-002 | 5.20 |
    2  | Lee  | Blue  | 001-002 | 4.50 |
    3  | Mel  | Blue  | 001-003 | 3.00 |
    4  | Joe  | Green | 001-001 | 2.00 |
    5  | Mike | Blue  | 001-002 | 1.00 |
    ------------------------------------

如何让它看起来像这样:?

--------------------------------
 Account | Red  | Blue | Green |
 001-001 | 0.00 | 0.00 | 2.00  |
 001-002 | 5.20 | 5.50 | 0.00  |
 001-003 | 0.00 | 3.00 | 0.00  |
--------------------------------

2 个答案:

答案 0 :(得分:2)

如果您有特定的颜色列表,则可以使用条件聚合:

select account,
       sum(case when color = 'blue' then amt else 0 end) as blue,
       sum(case when color = 'red' then amt else 0 end) as red,
       sum(case when color = 'green' then amt else 0 end) as green
from mytable
group by Account;

如果您没有列表,那么您可能需要查看动态SQL。

编辑:

在MS Access中,您可以使用iif()

执行相同的想法
select account,
       sum(iif(color = 'blue', amt, 0) as blue,
       sum(iif(color = 'red', amt, 0) as red,
       sum(iif(color = 'green', amt, 0) as green
from mytable
group by Account;

答案 1 :(得分:0)

您可以尝试使用PIVOT

SELECT Account,
      coalesce([Red],0) 'Red',
      coalesce([Blue],0) 'Blue',
      coalesce([Green],0) 'Green'
FROM (
   SELECT Account,color,SUM(Amt) Amt
   FROM T
   group by Account,color
) t
PIVOT(
  SUM(t.Amt) FOR color IN ([Red],[Blue],[Green])
)p1 

sqlfiddle:http://sqlfiddle.com/#!18/699a6/4