SQL - 计数出现数列

问题描述:

我有一个表,如下所示: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

喜欢的东西:

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” 只需要每行计算一次。另外,这可能不是很有效。

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 

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