grouping sets主要是用来合并多个分组的结果。
对于员工目标业绩表‘businessTarget’:
employeeId targetDate idealDistAmount
10098 2016-05 100000
10099 2016-05 80000
10100 2016-05 80000
10101 2016-05 100000
10102 2016-05 50000
10103 2016-05 50000
10104 2016-05 50000
10118 2016-05 50000
10130 2016-05 507689
10091 2016-07 20000
10290 2016-08 20000
10291 2016-08 20000
9058 2016-08 10000
9792 2016-07 20000
9865 2016-07 20000
如果需要分别对上表employeeId,targetDate,(employeeId,targetDate)分别进行group by,代码如下:
select employeeId,null,sum(idealDistAmount)
from businessTarget
group by employeeId
union all
select null,targetDate,sum(idealDistAmount)
from businessTarget
group by targetDate
union all
select employeeId,targetDate,sum(idealDistAmount)
from businessTarget
group by employeeId,targetDate
结果:
employeeId (无列名) (无列名)
9058 NULL 10000
9792 NULL 20000
9865 NULL 20000
10091 NULL 20000
10098 NULL 100000
10099 NULL 80000
10100 NULL 80000
10101 NULL 100000
10102 NULL 50000
10103 NULL 50000
10104 NULL 50000
10118 NULL 50000
10130 NULL 507689
10290 NULL 20000
10291 NULL 20000
NULL 2016-05 1067689
NULL 2016-07 60000
NULL 2016-08 50000
10098 2016-05 100000
10099 2016-05 80000
10100 2016-05 80000
10101 2016-05 100000
10102 2016-05 50000
10103 2016-05 50000
10104 2016-05 50000
10118 2016-05 50000
10130 2016-05 507689
9792 2016-07 20000
9865 2016-07 20000
10091 2016-07 20000
9058 2016-08 10000
10290 2016-08 20000
10291 2016-08 20000
如果我们运用grouping sets来指定多个group by 选项,
就可以通过一条select 语句实现复杂繁琐的多条select 语句的查询,并且更加的高效。
select employeeId,targetDate,sum(idealDistAmount)
from businessTarget
group by
grouping sets
(
(employeeId),
(targetDate),
(employeeId,targetDate),()
)
结果:
employeeId targetDate (无列名)
10098 2016-05 100000
10099 2016-05 80000
10100 2016-05 80000
10101 2016-05 100000
10102 2016-05 50000
10103 2016-05 50000
10104 2016-05 50000
10118 2016-05 50000
10130 2016-05 507689
NULL 2016-05 1067689
9792 2016-07 20000
9865 2016-07 20000
10091 2016-07 20000
NULL 2016-07 60000
9058 2016-08 10000
10290 2016-08 20000
10291 2016-08 20000
NULL 2016-08 50000
NULL NULL 1177689
9058 NULL 10000
9792 NULL 20000
9865 NULL 20000
10091 NULL 20000
10098 NULL 100000
10099 NULL 80000
10100 NULL 80000
10101 NULL 100000
10102 NULL 50000
10103 NULL 50000
10104 NULL 50000
10118 NULL 50000
10130 NULL 507689
10290 NULL 20000
10291 NULL 20000
除了grouping sets从属子句,我们还可以运用另外一个从属子句同样可以得到这样的结果,
那就是cube从属子句,代码如下:
select employeeId,targetDate,sum(idealDistAmount)
from businessTarget
group by
cube(employeeId,targetDate)--等同于grouping sets((employeeId),(targetDate),(employeeId,targetDate),())
order by employeeId
此三种方法运行得到的结果是一样的。