viv_acious
viv_acious

Reputation: 2489

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.

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".

In the above example, I would get a count of 3 for "ab" and count of 2 for "cd".

Upvotes: 3

Views: 2611

Answers (3)

Stv
Stv

Reputation: 506

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

Upvotes: 0

Brian Webster
Brian Webster

Reputation: 30855

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

Upvotes: 3

DaveShaw
DaveShaw

Reputation: 52788

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. Also, it's probably not very efficient.

Upvotes: 7

Related Questions