2

我正在尝试查询以找出有多少人在状态 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

任何建议将不胜感激。提前致谢。

4

2 回答 2

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

这是一个带有演示的 sqlfiddle 。结果是:

╔═══════════╦════════════════╗
║ PERSON_ID ║ NO_OF_STATUS_3 ║
╠═══════════╬════════════════╣
║         1 ║              2 ║
║         2 ║              1 ║
║         3 ║              0 ║
╚═══════════╩════════════════╝
于 2013-11-13T20:59:28.667 回答
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
于 2013-11-13T20:59:22.437 回答