SAP HANA SQL语句UNION 和 UNION ALL的用法

UNION ALL--不合并重复行

Selects all records from all selectstatements. Duplicates are not removed


UNION [DISTINCT] --合并重复行UNION 和 UNION DISTINCT功能相同

Selects all unique records from all selectstatements by removing duplicates found from different select statements. UNION has the same function as UNION DISTINCT.

合并重复行

select * from A union select * from B 

不合并重复行 select * from A union all select * from B 

按某个字段排序 --合并重复行

select * from ( select * from A union select * from B) AS T order by 字段名

不合并重复行

select * from ( select * from A union all select * from B) AS T order by 字段名

create column table t1 ( id int primary key, customer varchar(5), year int, product varchar(5), sales int );
 insert into t1 values(1, 'C1', 2009, 'P1', 100);
 insert into t1 values(2, 'C1', 2009, 'P2', 200);
 insert into t1 values(3, 'C1', 2010, 'P1', 50);
 insert into t1 values(4, 'C1', 2010, 'P2', 150);
 insert into t1 values(5, 'C2', 2009, 'P1', 200);
 insert into t1 values(6, 'C2', 2009, 'P2', 300);
 insert into t1 values(7, 'C2', 2010, 'P1', 100);
 insert into t1 values(8, 'C2', 2010, 'P2', 150);
 create column table t2 ( id int primary key, customer varchar(5), year int, product varchar(5), sales int );
  insert into t2 values(1, 'C1', 2011, 'P1', 100);
 insert into t2 values(2, 'C1', 2011, 'P2', 200);
 insert into t2 values(3, 'C1', 2011, 'P1', 50);
 insert into t2 values(4, 'C1', 2011, 'P2', 150);
 insert into t2 values(5, 'C2', 2011, 'P1', 200);
 insert into t2 values(6, 'C2', 2011, 'P2', 300);
 insert into t2 values(7, 'C2', 2011, 'P1', 100);
 insert into t2 values(8, 'C2', 2011, 'P2', 150);
 insert into t2 values(9, 'C1', 2011, 'P1', 100);

 select count(1) from (select  customer,year,product,sales from t1 union select  customer,year,product,sales from t2)    结果--->> 16

 select count(1) from (select  customer,year,product,sales from t1  UNION DISTINCT select  customer,year,product,sales from t2)  结果 --->> 16

 select count(1) from (select  customer,year,product,sales from t1 union all select  customer,year,product,sales from t2)  结果-->>17

select top 10 * from (select  customer,year,product,sales from t1 union all select  customer,year,product,sales from t2) order by customer

结果

CUSTOMER;YEAR;PRODUCT;SALES
C1;2009;P1;100
C1;2011;P2;150
C1;2011;P1;50
C1;2011;P2;200
C1;2011;P1;100
C1;2010;P1;50
C1;2009;P2;200
C1;2010;P2;150
C1;2011;P1;100
C2;2010;P2;150

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值