SQL 最后一行的分组和条件总和

SQL group and condition sum in the last row

我有几个项目属于不同的组,有些是未知组。 我需要按日期计算每组的总和。 我只是尝试以下 SQL 但仍然不是我想要的:

with A as (
SELECT PG, EMANAGER_DATE,
  CASE WHEN (EMANAGER_DATE = '2021-09') THEN SUM(NET_VALUE_USD) ELSE 0 END AS "2021-09",
  CASE WHEN (EMANAGER_DATE = '2021-10') THEN SUM(NET_VALUE_USD) ELSE 0 END AS "2021-10",
  CASE WHEN (EMANAGER_DATE = '2021-11') THEN SUM(NET_VALUE_USD) ELSE 0 END AS "2021-11",
  CASE WHEN (EMANAGER_DATE = '2021-12') THEN SUM(NET_VALUE_USD) ELSE 0 END AS "2021-12"
  FROM table1
  GROUP BY PG, EMANAGER_DATE
)
select PG, max("2021-09") AS "2021-09", max("2021-10") AS "2021-10", max("2021-11") AS "2021-11", max("2021-12") AS "2021-12" from A GROUP BY PG

数据库:SAP HANA

数据:

Item PG NET_VALUE_USD EMANAGER_DATE
1 1 100 2021-09
2 1 200 2021-10
3 2 300 2021-09
4 2 400 2021-09
5 3 500 2021-09
6 3 200 2021-11
7 3 300 2021-11
8 900 2021-09

预期结果:

PG 2021-09 2021-10 2021-11
? 900 0 0
1 100 200 0
2 700 0 0
3 500 0 500
total 2200 200 500

您可以调整查询并使用 GROUPING SETS:

SELECT (CASE WHEN GROUPING(PG) = 1 THEN 'Total' ELSE PG END) as PG,
       SUM(CASE WHEN EMANAGER_DATE = '2021-09' THEN NET_VALUE_USD ELSE 0 END) AS "2021-09",
       SUM(CASE WHEN EMANAGER_DATE = '2021-10' THEN NET_VALUE_USD ELSE 0 END) AS "2021-10",
       SUM(CASE WHEN EMANAGER_DATE = '2021-11' THEN NET_VALUE_USD ELSE 0 END) AS "2021-11",
       SUM(CASE WHEN EMANAGER_DATE = '2021-12' THEN NET_VALUE_USD ELSE 0 END) AS "2021-12"
FROM _SYS_BIC."APP_SCM/ZCV_APP_SCM_CTOS_PARENT_UNCONFIRMED_BACKLOG_P"
GROUP BY GROUPING SETS ( (PG), () );