using(select+)+oracle,Oracle SQL - Generate aggregate rows for certain rows using select

博客介绍了如何在不使用UNION的情况下,利用GROUPING SETS在SQL查询中进行多级数据分组和汇总。通过GROUPING函数来识别不同级别的输出行,示例展示了在FILE、ID、PARENTID和SHOWCHILD四个字段上的分组,以及针对CAT1、CAT2、CAT3和TOTAL的聚合计算,最终生成包括单个总计行在内的结果。
摘要由CSDN通过智能技术生成

I see you already accepted an answer, but you did ask for a solution that did not involve UNION. One such solution would be to use GROUPING SETS.

GROUPING SETS allow you to specify different grouping levels in your query and generate aggregates at each of those levels. You can use it to generate an output row for each record plus a single "total" row, as per your requirements. The function GROUPING can be used in expressions to identify whether each output row is in one group or the other.

Example, with test data:

with input_data ("FILE", "ID", PARENTID, SHOWCHILD, CAT1, CAT2, CAT3, TOTAL ) AS (

SELECT 'F1','A1','P1','N',3,2,6,11 FROM DUAL UNION ALL

SELECT 'F2','A2','P2','N',4,7,3,14 FROM DUAL UNION ALL

SELECT 'F3','A3','P1','N',3,1,1,5 FROM DUAL UNION ALL

SELECT 'F4','LG1','','Y',6,3,7,16 FROM DUAL UNION ALL

SELECT 'F5','LG2','','Y',4,7,3,14 FROM DUAL )

SELECT decode(grouping("FILE"),1,'Tot',"FILE") "FILE",

decode(grouping("ID"),1,'Res',"ID") "ID",

decode(grouping(parentid),1, 'Res',parentid) parentid,

decode(grouping(showchild),1, 'N',showchild) showchild,

decode(grouping("FILE"),1,sum(decode(showchild,'Y',cat1,0)),sum(cat1)) cat1,

decode(grouping("FILE"),1,sum(decode(showchild,'Y',cat2,0)),sum(cat2)) cat2,

decode(grouping("FILE"),1,sum(decode(showchild,'Y',cat3,0)),sum(cat3)) cat3,

decode(grouping("FILE"),1,sum(decode(showchild,'Y',total,0)),sum(total)) total

from input_data

group by grouping sets (("FILE", "ID", parentid, showchild), ())

+------+-----+-----+----------+-----------+------+------+------+-------+

| FILE | F2 | ID | PARENTID | SHOWCHILD | CAT1 | CAT2 | CAT3 | TOTAL |

+------+-----+-----+----------+-----------+------+------+------+-------+

| F1 | F1 | A1 | P1 | N | 3 | 2 | 6 | 11 |

| F2 | F2 | A2 | P2 | N | 4 | 7 | 3 | 14 |

| F3 | F3 | A3 | P1 | N | 3 | 1 | 1 | 5 |

| F4 | F4 | LG1 | - | Y | 6 | 3 | 7 | 16 |

| F5 | F5 | LG2 | - | Y | 4 | 7 | 3 | 14 |

| Tot | Tot | Res | Res | N | 10 | 10 | 10 | 30 |

+------+-----+-----+----------+-----------+------+------+------+-------+

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值