SQL:插入带有汇总值的行

时间:2018-05-04 12:07:25

标签: sql oracle group-by grouping

请查看我的第一个问题:SQL: partition over two columns

我有以下表格:

----------------------------------
| 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                      |
----------------------------------------------------

请注意,可以有多行,例如值(No1 = A,No2 = B)

更新:添加时间戳列以更具体地实现我想要实现的目标

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

一种方法是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);