两表union 如何保证group by 字段唯一

当要计算的指标可能来源多个表时,可能会使用到union all把不同的表中计算的指标合起来。关于union all使用条件:两个要联合的SQL语句 字段个数必须一样,而且字段类型要“相容”(一致)

另外,回顾union和union all的区别:union会自动压缩多个结果集合中的重复结果,而union all则将所有的结果全部显示出来,不管是不是重复。

Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序;
Union All:对两个结果集进行并集操作,包括重复行,不进行排序;

如何保证要进行分组的字段唯一呢?
常用两种写法:
写法一:group by之后union all ,之后再次group by保证分组字段的唯一

select
	group_key,sum(index_a),sum(index_b)
from(
	select 
		group_key,index_a,0 as index_b
	from a
	group by group_key
	union all
	select 
		group_key,0 as index_a,index_b
	from a
	group by group_key
)
group by group_key
;

写法二:开始不分组,将查到的分组字段union all 之后group by

select
from
(
    select
        group_by_key
    from
    (
        select
            group_by_key
        from t1
        union all
        select
            group_by_key
        from t2
    )a
    group by group_by_key
)a
left outer join t1
left outer join t2

猜你喜欢

转载自blog.csdn.net/weixin_43629813/article/details/132669648