使用Where like对同一列进行多次计数 - MySQL
我正在尝试使用不同的 where like 子句对同一列进行多次计数。
我已经弄清楚了每个类似子句的基本查询,但我需要将它们组合起来以产生一个结果。
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%';
我确信这是可能的,我只是不知道该怎么做。任何帮助将不胜感激。
提前感谢
更新:
这最终对我有用,
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;
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 SUM/Case 来“旋转”计数
注意:如果没有通配符,我不会费心使用“Like”
You can use SUM/Case to "pivot" the counts
Note: I wouldn't bother to use "Like" without the wild cards
您可以使用 SUM/CASE 组合来实现所需的结果,如答案 https://stackoverflow.com/a/8870028/ 625594。
对于您的情况,确切的查询将是:
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:
你可以这样写:
由于
system_user
大概都是相同的,MAX()
只会随机得到一个,它解决了无法将聚合列与非聚合列组合起来。You could write it like this:
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.