簡體   English   中英

SQL - 計算列中出現的次數

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

我有一張表如下:

我想在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

我希望有2列... 1表示“ab”,1表示“cd”。

在上面的例子中,“ab”的計數為3,“cd”的計數為2。

就像是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM