简体   繁体   English

SQL - 计算列中出现的次数

[英]SQL - count number of occurrences in a column

I have a table as follows: 我有一张表如下:

and I want to count the occurrences of say "ab" and "cd" in the column PageURL. 我想在PageURL列中计算说“ab”和“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

I want to have 2 columns...1 for count of "ab" and 1 for count of "cd". 我希望有2列... 1表示“ab”,1表示“cd”。

In the above example, I would get a count of 3 for "ab" and count of 2 for "cd". 在上面的例子中,“ab”的计数为3,“cd”的计数为2。

Something like: 就像是:

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%'

This works assuming "ab" and "cd" only need to be counted once per row. 这可以假设“ab”和“cd”只需要每行计数一次。 Also, it's probably not very efficient. 而且,它可能效率不高。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM