db2 SQL -为第1列中的每个非重复值添加总计行

y0u0uwnf  于 2022-11-07  发布在  DB2
关注(0)|答案(2)|浏览(167)

我试图为来自我的第一列的每个非重复值添加一个“total count”行。我尝试创建一个UNION ALL,但却把事情弄得一团糟。(基于TL.OP_CODE值。)任何帮助都非常感谢。对我的格式设置感到抱歉...

select 
tl.op_code as "OPS Code",  tl.current_status AS "Status", tl.service_level as "Service",
tl.Bill_number as "Bill number", tl.trace_no as "Trace No", 
tl.pick_up_by  AS "PU By", tl.origname, tl.origcity, tl.origprov,
tl.deliver_by AS "DEL By", tl.destname, tl.destcity, tl.destprov, tl.pallets 
from tlorder tl
where tl.current_Status NOT IN ('CANCL')
order by tl.op_code, tl.currency_code, tl.pick_up_by
mwkjh3gx

mwkjh3gx1#

请尝试以下方法:

WITH MYTAB (op_code, A, B) AS
(
-- You may put your original SELECT here 
-- instead of this artificial VALUES
VALUES
  (1, 1, 1)
, (1, 1, 2)
, (2, 1, 1)
) 
SELECT op_code, A, B, CAST (NULL AS INT) AS CNT
FROM MYTAB T
  UNION ALL
SELECT op_code, NULL, NULL, COUNT (1) CNT  
FROM MYTAB
GROUP BY op_code
ORDER BY op_code, CNT DESC;

| 操作代码|A级|B|碳纳米管|
| - -|- -|- -|- -|
| 一个|一个|一个||
| 一个|一个|2个||
| 一个|||2个|
| 2个|一个|一个||
| 2个|||一个|

kcrjzv8t

kcrjzv8t2#

例如,如果我有student_score表,并且我试图在此处获得不同分数的分数总和,则使用Rollup。

| student_id | score |
| ---------- | ----- |
| 1          | 95    |
| 2          | 95    |
| 3          | 95    |
| 4          | 93    | 
| 5          | 93    |
| 6          | 98    |
| 7          | 98    |
| 8          | 99    |
| 9          | 91    |
| 10         | 91    |

SELECT student_id, sum(score) as score from student_score GROUP BY ROLLUP(score, student_id) ORDER BY score;

| student_id | score |
| ---------- | ----- |
| NULL       | 948   |
| 9          | 91    |
| 10         | 91    |
| NULL       | 182   |  
| 4          | 93    |
| 5          | 93    |
| NULL       | 186   |
| 1          | 95    |
| 2          | 95    |
| 3          | 95    |
| NULL       | 285   |
| 6          | 98    |
| 7          | 98    |
| NULL       | 196   |  
| 8          | 99    |
| NULL       | 99    |

相关问题