关键字:
KingbaseES、GROUPING_ID、人大金仓
语法
GROUPING(args…..)
GROUPING将超聚合行与常规分组行区分开来。GROUP BY扩展(如ROLLUP和CUBE)生成超聚合行,其中所有值的集合由null表示。使用GROUPING函数,可以将表示超聚合行中所有值的集合的空值与常规行中的空值区分开来。GROUPING函数中的args必须匹配GROUP BY子句中的表达式之一。如果该行中args的值表示所有值的集合的空值,则该函数返回值1,否则,它返回0。
ROLLUP和CUBE是GROUP BY子句的扩展,例如GROUP BY ROLLUP(expr1,expe2...)。ROLLUP操作根据GROUP BY规范中的前n,n-1,n-2,...0个表达式的值进行分组,并为每个分组返回一行摘要。其中,前n个表达式的值分组的行称为常规行,其他行称为超聚合行。
CUBE和ROLLUP的区别是CUBE对所有可能的表达式组合的值进行分组。例如GROUP BY CUBE(A,B,C),首先会对(A,B,C)进行GROUP BY,然后依次是(A,B), (A,C), (A), (B,C), (B), (C)进行GROUP BY,最后对全表进行GROUP BY。其使用方式和ROLLUP一致。
规则
(1)分组操作用来与分组集合(如CUBE和ROLLUP)共同来区分结果行。GROUPING操作的参数并不会被实际计算,但是它们必须准确地匹配在相关查询层次的GROUP BY子句中给定的表达式。最右边参数指派的位是最低有效位,如果对应的表达式被包括在产生结果行的分组集合的分组条件中则每一位是 0,否则是 1。
(2)GROUPING_ID函数和GROUPING函数的使用范围一致。GROUPING_ID和GROUPING函数的参数个数最大为31个参数。新增的GROUPING_ID关键词与GROUPING一致,为非保留关键词(不可以是函数或类型)。
数据准备
(1)创建数据表并插入数据
test=# create table items_sold (make varchar(10), model varchar(10), sales number);
CREATE TABLE
test=# insert into items_sold values('Foo', 'GT', 10);
INSERT 0 1
test=# insert into items_sold values('Foo', 'Tour', 20);
INSERT 0 1
test=# insert into items_sold values('Bar', 'City', 15);
INSERT 0 1
test=# insert into items_sold values('Bar', 'Sport', 5);
INSERT 0 1
test=# insert into items_sold values('Bar', NULL, 5);
INSERT 0 1
(2)查看数据表
test=# select * from items_sold;
make | model | sales
------+-------+-------
Foo | GT | 10
Foo | Tour | 20
Bar | City | 15
Bar | Sport | 5
Bar | | 5
(5 rows)
测试用例
(1)
test=# select make,model,sum(sales),grouping(make) as gma, grouping(model) as gmo,grouping_id(model,make) from items_sold group by rollup(make,model) order by make,model;
make | model | sum | gma | gmo | grouping_id
------+-------+-----+-----+-----+-------------
Bar | City | 15 | 0 | 0 | 0
Bar | Sport | 5 | 0 | 0 | 0
Bar | | 25 | 0 | 1 | 2
Bar | | 5 | 0 | 0 | 0
Foo | GT | 10 | 0 | 0 | 0
Foo | Tour | 20 | 0 | 0 | 0
Foo | | 30 | 0 | 1 | 2
| | 55 | 1 | 1 | 3
(8 rows)
(2)
test=# select make,model,sum(sales),grouping(make) as gma, grouping(model) as gmo,grouping_id(model,make) from items_sold group by rollup(make,model) having grouping_id(model,make) = 2 order by make,model ;
make | model | sum | gma | gmo | grouping_id
------+-------+-----+-----+-----+-------------
Bar | | 25 | 0 | 1 | 2
Foo | | 30 | 0 | 1 | 2
(2 rows)
test=# SELECT make, model, GROUPING(make,model), sum(sales) FROM items_sold GROUP BY ROLLUP(make,model);
make | model | grouping | sum
------+-------+----------+-----
| | 3 | 55
Foo | Tour | 0 | 20
Foo | GT | 0 | 10
Bar | Sport | 0 | 5
Bar | City | 0 | 15
Bar | | 0 | 5
Foo | | 1 | 30
Bar | | 1 | 25
(8 rows)