2016-11-27 60 views
1

如果我從多個表中獲取列,如何按列和按頻率排序?例如,我有3個表格,Table_A,Table_B,Table_C。他們每個人都有一列相同的數據。 e.g表-A如何使用多個表進行分組和排序

col 
------ 
aaa 
bbb 
aaa 
ccc 

e.g表-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

首先,使用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; 
+0

戈登,這是一個總的括號一塌糊塗... –

+0

@DuduMarkovitz。 。 。我將描述如何在*數據分析使用SQL和Excel *的第1章中縮進我的代碼。改變我寫代碼的方式,請不要對我有任何幫助。我讚賞所做的任何小改動,但對縮進風格感到不滿。 –

+0

我不會改變風格。第一次更改是針對ORDER BY的。第二個變化是因爲由於括號不匹配導致代碼無效,當所有的括號實際上是多餘的。我也寫了我自己的答案,它基本上是相同的代碼(但工作......),但一分鐘後我刪除了它,因爲我不想在你的鼻子下偷一個正確的答案。 –

-1

每一個選擇的子句需要自己組。

選擇欄,計數()從表-A 組 由COL UNION 選擇欄,計數()從表-B 組 由COL UNION 選擇欄,從Table_C 組COUNT(*) by col order by 2 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 
; 
相關問題