SQL: insert rows with summarized values

断了今生、忘了曾经 提交于 2019-12-13 02:49: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);


来源:https://stackoverflow.com/questions/50174587/sql-insert-rows-with-summarized-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!