VastbaseG100

基于openGauss内核开发的企业级关系型数据库。

Menu

GROUP BY特性增强

功能描述

在Vastbase现有group by功能的基础上增强对Oracle group by子句的兼容。针对含有子查询的分组列,不仅支持普通的列,且:

  • 支持含有表达式或者函数的列。

  • 支持忽略group by后接的常量和NULL,即处理方式与Oracle保持一致。其中常量包括数字、中文、英文。本特性通过enable_ora_group参数控制,当取值为true时开启本特性。

    • enable_ora_group=off时,对group by后接常量和NULL进行相应处理,将常量当做查询列的序号,序号不合法时将报错。

    • enable_ora_group=on时,忽略group by后接的常量和NULL,不报错也不处理。

注意事项

  • 以上特性仅在数据库兼容模式为Oracle时能够使用(即创建DB时DBCOMPATIBILITY='A'),在其他数据库兼容模式下不能使用该特性。

  • 忽略group by后接的常量和NULL特性仅在Vastbase V2.2 Build 10(Patch No.17)及以后版本支持。

语法格式

select [grouping_element],
[expression] 
[WHERE condition]
[from table]
group by [grouping_element];

参数说明

  • grouping_element

    函数、表达式、常量和NULL。其中在参数enable_ora_group取值为true时常量和NULL会被直接忽略。

  • expression

    SQL语句中的子查询。

示例

示例1 使用分组列中包含函数。

1、创建并切换至兼容模式为ORACLE的数据库db_oracle。

CREATE DATABASE db_oracle dbcompatibility='A';     
\c db_oracle

2、创建测试表并插入数据。

create table test_a(c1 number,c2 varchar2(20));
insert into test_a values(1,'a');
insert into test_a values(2,'a_xxr');
insert into test_a values(3,'a_ytr');
insert into test_a values(4,'b');
insert into test_a values(5,'b_xxr');
insert into test_a values(6,'b_ytr');
create table test_b(c1 number,c2 varchar2(20));
insert into test_b values(11,'a');
insert into test_b values(22,'b');
insert into test_b values(33,'aa');
insert into test_b values(44,'ba');
insert into test_b values(55,'e');
insert into test_b values(66,'f');

3、使用group by子句包含函数。

SELECT substr(a.c2, 1, 1)
        , (
                SELECT b.c1
                FROM test_b b
                WHERE b.c2 = substr(a.c2, 1, 1)
        )
FROM test_a a
GROUP BY substr(a.c2, 1, 1);

返回结果为:

 substr | c1
--------+----
 a      | 11
 b      | 22
(2 rows)

4、清理环境。

\c postgres
DROP DATABASE db_oracle;

示例2 group by 后接常量。

1、创建并切换至兼容模式为ORACLE的数据库db_oracle。

CREATE DATABASE db_oracle dbcompatibility='A';     
\c db_oracle

2、创建测试表并插入数据。

create table t_test(id integer,cnt integer);
insert into t_test values (1,1);
insert into t_test values (1,22);
insert into t_test values (2,1);
insert into t_test values (2,16);
insert into t_test values (3,13);
insert into t_test values (3,1);

3、查询测试数据,其中子查询的分组列中含有常量和null,此时本查询语句将提示报错。

select id,sum(cnt),'折扣折让金额合计',1 as comefrom from t_test group by id,2,2.1,'折扣折让金额合计',0,790,null;

4、开启参数并再次执行子查询带有常量和null的查询语句。

set enable_ora_group=on;
show enable_ora_group;
select id,sum(cnt),'折扣折让金额合计',1 as comefrom from t_test group by id,2,2.1,'折扣折让金额合计',0,790,null;

返回结果为:

 enable_ora_group
-------------------
 on
(1 row)

 id | sum |     ?column?    | comefrom
----+-----+-----------------+---------
 1  | 23  | 折扣折让金额合计 |  1
 2  | 14  | 折扣折让金额合计 |  1
 3  | 17  | 折扣折让金额合计 |  1
(3 rows)

5、清理环境。

\c postgres
DROP DATABASE db_oracle;