我正在尝试进行查询,以了解有多少人在状态3中有活动。我认为我需要COUNT或SUM,但是自从我之前做了很长时间后我已经尝试过搜索很多,但我仍然感到困惑。假设我有以下内容。
活动表:
activity_id status
1 3
2 3
3 1
Person_activity表:
person_id activity_id
1 1
1 2
2 2
2 3
3 3
我想要输出查询:
person_id no_of_status_3
1 2
2 1
3 0
任何建议都将不胜感激。提前谢谢。
答案 0 :(得分:4)
这应该做:
SELECT PA.person_id,
COUNT(A.activity_id) no_of_status_3
FROM Person_activity PA
LEFT JOIN ( SELECT *
FROM Activity
WHERE status = 3) A
ON PA.activity_id = A.activity_id
GROUP BY PA.person_id
Here is an sqlfiddle以及此演示。结果是:
╔═══════════╦════════════════╗
║ PERSON_ID ║ NO_OF_STATUS_3 ║
╠═══════════╬════════════════╣
║ 1 ║ 2 ║
║ 2 ║ 1 ║
║ 3 ║ 0 ║
╚═══════════╩════════════════╝
答案 1 :(得分:1)
SELECT pa.person_id, count(a.activity_id)
FROM person_activity pa
LEFT JOIN activity a ON (pa.activity_id = a.activity_id AND a.status = 3)
GROUP BY pa.person_id