2011-05-25 51 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