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!
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With