sql求分类跟合计:rollup()函数-阿里云开发者社区

开发者社区> 数据库> 正文
登录阅读全文

sql求分类跟合计:rollup()函数

简介: 使用rollup()函数

需求:按照地区code分组求个数,并包括合计,先解释下rollup()函数,比group by 多一个总计



select

area_code,

   sum(CASE WHEN owner_type = 0 THEN 1 ELSE 0 END) as legalPersonNum,

   sum(CASE WHEN owner_type = 1 THEN 1 ELSE 0 END) as adminNum

from licence_manager.business_licence_phone_entity

where area_code is not null and area_code != ''

group by rollup(area_code)

image.png


1、第一种,采用union


select

'合计' as area_code,sum(legalPersonNum) as legalPersonNum,

sum(adminNum) as adminNum

from(

select

    area_code,

    sum(CASE WHEN owner_type = 0 THEN 1 ELSE 0 END) as legalPersonNum,

    sum(CASE WHEN owner_type = 1 THEN 1 ELSE 0 END) as adminNum

from licence_manager.business_licence_phone_entity

where area_code is not null and area_code != ''

group by area_code

order by area_code

)

union

select

   area_code,

   sum(CASE WHEN owner_type = 0 THEN 1 ELSE 0 END) as legalPersonNum,

   sum(CASE WHEN owner_type = 1 THEN 1 ELSE 0 END) as adminNum

from licence_manager.business_licence_phone_entity

where area_code is not null and area_code != ''

group by area_code

order by area_code


image.png


2、采用rollup()函数


select

   decode(grouping(area_code),1,'total',area_code) as area_code,

   sum(CASE WHEN owner_type = 0 THEN 1 ELSE 0 END) as legalPersonNum,

   sum(CASE WHEN owner_type = 1 THEN 1 ELSE 0 END) as adminNum

from licence_manager.business_licence_phone_entity

where area_code is not null and area_code != ''

group by rollup(area_code)

order by area_code


image.png





版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
数据库
使用钉钉扫一扫加入圈子
+ 订阅

分享数据库前沿,解构实战干货,推动数据库技术变革

其他文章
最新文章
相关文章