3

I'm trying to do multiple counts on the same column with different where like clauses.

I have figured out the base Queries for each of my like clauses but I need to combine them to produce one result.

select system_user, COUNT(details) from asset_log where details like 'Viewed';
select system_user, COUNT(details) from asset_log where details like 'Viewed Web%';
select system_user, COUNT(details) from asset_log where details like 'ThumbView';
select system_user, COUNT(details) from asset_log where details like 'Exported%';

I'm sure its possible, I just dont know how to do it. Any help would be appreciated.

Thanks In Advance

Update:

this Ended up working for me

select distinct system_user, 
    SUM(CASE WHEN details ='viewed' then 1 Else 0 end) AS viewed_count,
    SUM(CASE WHEN details Like 'Viewed Web%' then 1 Else 0 end) AS Web_count,
    SUM(CASE WHEN details = 'ThumbView' then 1 Else 0 end) AS ThumbView_count,
    SUM(CASE WHEN details Like 'Exported%' then 1 Else 0 end) AS Exported_count
from asset_log GROUP BY system_user; 

Thanks!

rreeves
  • 2,408
  • 6
  • 39
  • 53

3 Answers3

6

You can use SUM/Case to "pivot" the counts

select system_user, 

    SUM(CASE WHEN details ='viewed' then 1 Else 0 end) viewed_count
    SUM(CASE WHEN details Like 'Viewed Web%' then 1 Else 0 end) Viewed Web_count
    SUM(CASE WHEN details = 'ThumbView' then 1 Else 0 end) ThumbView_count
    SUM(CASE WHEN details Like 'Exported%' then 1 Else 0 end) Exported_count
from asset_log 
where 
    details = 'viewed' or
    details like 'Viewed Web%' or
    details = 'ThumbView' or
    details like 'Exported%' 
 group by 
      system_user

Note: I wouldn't bother to use "Like" without the wild cards

Conrad Frix
  • 51,984
  • 12
  • 96
  • 155
1

You may use combintation of SUM/CASE to achieve the desired result, like in the answer https://stackoverflow.com/a/8870028/625594.

For your case the exact query will be:

select system_user, 
SUM(CASE WHEN details like 'Viewed' THEN 1 ELSE 0) AS `sum1`,  
SUM(CASE WHEN details like 'Viewed Web%' THEN 1 ELSE 0) AS `sum2`,
SUM(CASE WHEN details like 'ThumbView' THEN 1 ELSE 0) AS `sum3`,
SUM(CASE WHEN details like 'Exported%' THEN 1 ELSE 0) AS `sum4`
from asset_log;
Community
  • 1
  • 1
Sergey Kudriavtsev
  • 10,328
  • 4
  • 43
  • 68
1

You could write it like this:

SELECT MAX(system_user) AS system_user, COUNT(*)
  FROM asset_log
  WHERE details = 'Viewed'
  OR details like 'Viewed Web%'
  OR details = 'ThumbView'
  OR details like 'Exported%'

Since system_user are presumably all the same, MAX() will just get one at random, and it works around the problem of not being able to combine aggregate columns with non-aggregate columns.

Marcus Adams
  • 53,009
  • 9
  • 91
  • 143