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





相关文章
|
4天前
|
SQL 数据库
SQL SUM() 函数
SQL SUM() 函数
9 0
|
3天前
|
SQL 数据库
SQL LCASE() 函数
SQL LCASE() 函数
13 7
|
1天前
|
SQL 数据库
SQL FORMAT() 函数
SQL FORMAT() 函数
7 2
|
3天前
|
SQL 数据库
SQL UCASE() 函数
SQL UCASE() 函数
11 4
|
2天前
|
SQL
SQL ROUND() 函数
SQL ROUND() 函数
9 1
|
6天前
|
SQL Oracle 关系型数据库
SQL LAST() 函数
SQL LAST() 函数
14 5
|
7天前
|
SQL Oracle 关系型数据库
SQL FIRST() 函数
SQL FIRST() 函数
12 3
|
1天前
|
SQL 数据库
SQL NOW() 函数
SQL NOW() 函数
2 0
|
2天前
|
SQL 关系型数据库 MySQL
SQL LEN() 函数
SQL LEN() 函数
5 0
|
2天前
|
SQL 数据库
SQL MID() 函数
SQL MID() 函数
8 0