1

我想在具有不同过滤器的同一字段的查询中对“金额”字段使用SUM()函数4 次。 就像是



SELECT Date1,CC,BU, SUM(Amount),SUM(Amount),SUM(Amount),SUM(Amount)
FROM MainTable<br>
GROUP BY CC,BU,Date1

这里

1stSUM(Amount)应该计算Mode='011' And Mode='012'from MainTable
2ndSUM(Amount)应该计算Mode like '03_'And Mode Like '05_'from MainTable
3rdSUM(Amount)应该计算 when Mode like '10_'from MainTable
4thSUM(Amount)应该计算 when and (Mode !='011')from MainTable(Mode !='012') (Mode not Like '03_')(Mode not Like '05_')

如何做到这一点?我尝试了很多方法,但无法以我想要的方式得到结果。
请帮我。
先感谢您。

4

1 回答 1

7

您可以使用带有 a 的聚合函数CASE

SELECT Date1,
  CC,
  BU, 
  SUM(case when mode = '011' then Amount end) Mode011,
  SUM(case when mode = '012' then Amount end) Mode012,
  SUM(case when mode = '013' then Amount end) Mode013,
  SUM(case when mode = '014' then Amount end) Mode014
FROM MainTable
GROUP BY CC,BU,Date1;

或者您可以使用 PIVOT 功能:

select date1, CC, BU,
  [011] Mode011, 
  [012] Mode012, 
  [013] Mode013, 
  [014] Mode014
from
(
  select date1, CC, BU, mode, amount
  from maintable
) src
pivot
(
  sum(amount)
  for mode in ([011], [012], [013], [014])
) piv
于 2013-05-09T18:13:46.060 回答