如果从多个表中获取列,如何按列分组并按频率排序?例如,我有3个表,Table_A,Table_B,Table_C。它们中的每一个都有一列相同的数据。 例如Table_A
col
------
aaa
bbb
aaa
ccc
例如Table_B
aaa
ccc
ddd
bbb
同样是Table_C的类似数据。我希望得到以下结果:
aaa 3
bbb 2
ccc 2
ddd 1
目前,我有这个
select col, count(*) from Table_A UNION select col, count(*) from Table_B UNION select col, count(*) from Table_C group by col order by count(*) desc
但这并没有给我我想要的结果。感谢
答案 0 :(得分:2)
select col
,count(*) as cnt
from ( select col from Table_A
union all select col from Table_B
union all select col from Table_C
) t
group by col
order by cnt desc
,col
;
OR
select col
,sum(cnt) as sum_cnt
from ( select col,count(*) as cnt from Table_A group by col
union all select col,count(*) from Table_B group by col
union all select col,count(*) from Table_C group by col
)
group by col
order by sum_cnt desc
,col
;
答案 1 :(得分:0)
首先,使用union all
,然后进行聚合。正确的语法是:
select col, count(*) as cnt
from (select col from Table_A
union all
select col from Table_B
union all
select col from Table_C
) abc
group by col
order by col;
您也可以预先汇总数据,但需要再次汇总:
select col, sum(cnt) as sum_cnt
from (select col, count(*) as cnt from Table_A group by col
union all
select col, count(*) from Table_B group by col
union all
select col, count(*) from Table_C group by col
) abc
group by col
order by col;
答案 2 :(得分:-1)
每个select都需要自己的group by子句。
选择col,count() 来自Table_A 按组分组 联盟 选择col,count() 来自Table_B 按组分组 联盟 选择col,count(*) 来自Table_C 按组分组 按顺序排列;