2013-02-12 100 views
3

我有一個表,如下所示:SQL - 計數出現數列

,我想算的出現說「AB」,並在列PAGEURL「CD」。

ID User Activity PageURL Date 
1 Me act1  abcd  2013-01-01 
2 Me act2  cdab  2013-01-02 
3 You act2  xyza  2013-02-02 
4 Me act3  xyab  2013-01-03 

我想要有2列... 1爲計數的「ab」和1爲「cd」的計數。

在上面的例子中,「ab」的計數爲3,「cd」的計數爲2。

+0

「ab」或「cd」每行可以出現多次?如果是這樣,你認爲它是1還是數出現? – DaveShaw 2013-02-12 00:26:16

回答

6

喜歡的東西:

select 
    CountAB = sum(case when PageURL like '%ab%' then 1 else 0 end), 
    CountCD = sum(case when PageURL like '%cd%' then 1 else 0 end) 
from 
    MyTable 
where 
    PageURL like '%ab%' or 
    PageURL like '%cd%' 

這個工程假設 「AB」 和 「CD」 只需要每行計算一次。另外,這可能不是很有效。

2
select 
    (select count(*) as AB_Count from MyTable where PageURL like '%ab%') as AB_Count, 
    (select count(*) as CD_Count from MyTable where PageURL like '%cd%') as CD_Count 
0
SELECT total1, total2 
    FROM (SELECT count(*) as total1 FROM table WHERE PageUrl LIKE '%ab%') tmp1, 
     (SELECT count(*) as total2 FROM table WHERE PageUrl LIKE '%cd%') tmp2