2011-05-25 22 views
3

有包含相同類型的數據的2列:製作2列的查詢,就好像它們是一個

col_a col_b ... 
Bob Tim .. 
John Frank . 
Bob John 
John Tim 
Bob Bob 
Frank John 

現在我想做的查詢是這樣的(計算實例:(鮑勃,3 ),(約翰,2),..):

SELECT col_a, count(*) AS total FROM table1 GROUP BY col_a 

但不是在爲col_a運行它,我想在同一時間上爲col_a和col_b運行((鮑勃,4),(約翰,4 ),..)

任何幫助表示讚賞

編輯: 感謝每一個你真棒。

再次感謝根據您Bob Bob

回答

5
Select Z.name, Count(*) As Total 
From (
     Select col_a As name 
     From total 
     Union All 
     Select col_b 
     From total 
     ) As Z 
Group By Z.name 
+1

快速回答! Z作爲別名? ><讓我的頭受傷! – 2011-05-25 20:31:39

+1

@ N8 - 「Z」是任意的。只要您使用別名,就可以使用您喜歡的任何別名。 – Thomas 2011-05-25 20:34:44

4
select Name, count(*) as Total 
from (
    select col_a as Name from MyTable 
    union all 
    select col_b from MyTable 
) a 
group by Name 
+1

+1哦,這麼快,正確。 – Fosco 2011-05-25 20:30:19

1

,我認爲你需要組於子:

select idx, sum(count) 
from (
    select col_a as idx, count(*) as count 
    from table 
    union all 
    select col_b as idx, count(*) as count 
    where col_a <> col_b -- avoid dups 
    ) as counts 
group by idx 

或:

select idx, count(*) 
from (
    select col_a as idx 
    from table 
    union all 
    select col_b as idx 
    where col_a <> col_b -- avoid dups 
    ) as counts 
group by idx 
相關問題