我的数据库中有以下一组行:
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
换句话说:我想为每个用户检索“功能喜欢”和“功能跟随”的数量。
答案 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;