我有一张包含活动信息(姓名,日期,描述等)的表格和一张包含出勤信息的表格(人物,事件,他们是否参加)。我正在尝试从这两个表创建一个视图,以显示“是”的总数。回复和“不”的总数基于事件的回复。这是我到目前为止所做的。
SELECT e.id AS event, COUNT(yea.attendance) AS yes, COUNT(nea.attendance) AS no
FROM event_information e
LEFT JOIN event_attendance yea
ON e.id = yea.event_id AND yea.attendance = 'Y'
LEFT JOIN event_attendance nea
ON e.id = nea.event_id AND nea.attendance = 'N'
GROUP BY event;
所以我希望这会返回每个事件ID(1,2,3和4)以及相应的' yes'并且没有'响应。
event yes no
1 3 1
2 2 2
3 1 3
4 4 0
而是返回以下内容
event yes no
1 3 3
2 4 4
3 3 3
4 4 0
当我只加入event_attendance表一次以检索是或否结果时,则会输入正确的数字。只有当我重新加入同一张桌子时才会得到不正确的结果。
答案 0 :(得分:2)
改为使用条件聚合:
SELECT e.id AS event, SUM(a.attendance = 'Y') AS yes, SUM(a.attendance = 'N') AS no
FROM event_information e LEFT JOIN
event_attendance a
ON e.id = a.event_id A
GROUP BY event;
您的方法不起作用,因为它为每个事件生成“是”和“否”的笛卡尔积。如果任何一个类别中都有零个或一个,那么它应该有效。但是,如果两者都不止一个,那么你就会开始过度计算。
编辑:
此外,如果所有活动至少有一个出勤记录,那么您不需要join
:
SELECT a.event_id AS event,
SUM(a.attendance = 'Y') AS yes, SUM(a.attendance = 'N') AS no
FROM event_attendance a
GROUP BY event_id;
答案 1 :(得分:1)
看看是否有效:
SELECT e.id AS event
, SUM(CASE WHEN yea.attendance = 'Y' THEN 1 ELSE 0) AS yes
, SUM(CASE WHEN yea.attendance = 'N' THEN 1 ELSE 0) AS no
FROM event_information e
LEFT JOIN event_attendance a ON e.id = a.event_id
GROUP BY event;