SQL:插入带有汇总值的行(SQL: insert rows with summarized val

2019-10-29 23:09发布

请参阅我的第一个问题,我的话题: SQL:分区了两列

我有如下表:

----------------------------------
| No1 | No2  | Amount| Timestamp
----------------------------------
| A   |  B   |    10 |  01.01.2018
| C   |  D   |    20 |  02.01.2018
| B   |  A   |    30 |  03.01.2018
| D   |  C   |    40 |  04.01.2018
----------------------------------

我此刻的结果如下:

-----------------------------------------------------
| No1 | No2  | Sum(Amount) over partition | Timestamp
-----------------------------------------------------
| A   |  B   |    40                      | 01.01.2018
| C   |  D   |    60                      | 02.01.2018
| B   |  A   |    40                      | 03.01.2018
| D   |  C   |    60                      | 04.01.2018
-----------------------------------------------------

与SQL(从Vamsi Prabhala的回答第一个问题):

select no1,no2,sum(amount) over(partition by least(no1,no2),greatest(no1,no2)) as total, timestamp
from tbl

现在对我来说,问题是我怎么可以添加行的结果类似:

----------------------------------------------------
| No1 | No2  | Sum(Amount) over partition | Timestamp
----------------------------------------------------
| A   |  B   |    40  (optional)          | 01.01.2018
| B   |  A   |    40  (optional)          | 02.01.2018
| AB  |(NULL)|    40                      |
| C   |  D   |    60  (optional)          | 03.01.2018
| D   |  C   |    60  (optional)          | 04.01.2018
| CD  |(NULL)|    60                      |
----------------------------------------------------

请注意,可以存在与例如值(1号= A,NO 2 = B)的多个行

更新:加入时间戳列更具体的我想达到的目标

Answer 1:

SELECT
  LEAST(No1, No2) || ':' || GREATEST(No1, No2)     AS set_label,
  No1,
  No2,
  SUM(Amount)                               AS Amount,
  Stamp
FROM
  tbl
GROUP BY
  GROUPING SETS (
    (LEAST(No1, No2), GREATEST(No1, No2), No1, No2, Stamp),
    (LEAST(No1, No2), GREATEST(No1, No2))
  )

http://sqlfiddle.com/#!4/9afd5/18

会更好,如果每一行都有一个唯一的标识符...

http://sqlfiddle.com/#!4/e9e95/1



Answer 2:

一种方法是UNION ALL

select no1, no2,
       sum(amount) over (partition by least(no1, no2), greatest(no1, no2)) as total
from tbl
union all
select least(no1, no2) || greatest(no1, no2), NULL, sum(amount)
from tbl
group by least(no1, no2), greatest(no1, no2);


文章来源: SQL: insert rows with summarized values