计算包含特定字符串和聚合的行数

时间:2018-01-14 04:39:02

标签: mysql sql

我的数据库中有以下一组行:

 USER   |  ACTIVITY
'User1' | 'User1 liked FeatureX'
'User1' | 'User1 liked FeatureY'
'User2' | 'User2 followed FeatureX'

我想运行执行以下操作的查询:

select User, 
       count(Activity like '%liked%') as LikedActivity, 
       count(Activity like '%followed%') as FollowedActivity
from db.Table 
group by USER

换句话说:我想为每个用户检索“功能喜欢”和“功能跟随”的数量。

1 个答案:

答案 0 :(得分:1)

此处使用SUM以及CASE表达式:

SELECT
    User, 
    SUM(CASE WHEN Activity LIKE '%liked%'    THEN 1 ELSE 0 END) AS LikedActivity, 
    SUM(CASE WHEN Activity LIKE '%followed%' THEN 1 ELSE 0 END) AS FollowedActivity
FROM db.Table 
GROUP BY User;

我们也可以在这里使用COUNT,这会导致查询更加整洁:

SELECT
    User, 
    COUNT(CASE WHEN Activity LIKE '%liked%'    THEN 1 END) AS LikedActivity, 
    COUNT(CASE WHEN Activity LIKE '%followed%' THEN 1 END) AS FollowedActivity
FROM db.Table 
GROUP BY User;