简体   繁体   中英

Multiple Count On Same Column with Where like - MySQL

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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