SQL: insert rows with summarized values

2019-08-18 14:40发布

问题:

please see my first question to my topic: SQL: partition over two columns

I have following table:

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

I have the following results at the moment:

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

with the SQL (from the first question with Vamsi Prabhala's answer):

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

The question for me now is how can I add rows to the results like:

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

Please be aware that there can be multiple rows with for example the values (No1=A,No2=B)

UPDATE: added timestamp column to be more specific what I want to achieve

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

Would be better if each row has a unique identifier...

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



回答2:

One method is 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);