我知道这与这个问题类似:MySQL Query - Sum one related table - Count another related table但我不能让它对我有用。
我有3张桌子:
Event
Attendee
Gifts
对于每个Event
,我们需要总结Attendees
的数量以及Gifts
的总数。 Attendee
可能会或可能不会收到礼物。
我可以让它工作,这样如果我忽略礼物总数,我会得到正确的答案:
SELECT event.name AS name, count( * ) AS num_attendee
FROM attendee
RIGHT JOIN event on event.id = attendee.event_id
WHERE event.company_id =6
GROUP BY event.id
但我不知道如何将每个事件的所有Gift.Amount
的礼物(即Attendees
值)相加。当我尝试简单地加入基于Gift
的{{1}}表时,所有数字都是古怪的。
答案 0 :(得分:0)
你正在进行正确的连接吗?您应该在礼物表中同时拥有活动和与会者:
from attendee right join
event
on event.id = attendee.event_id right join
gifts
on event.id = gifts.event_id and attendee.id = gifts.attendee_id
答案 1 :(得分:0)
这是MS-SQL 2000中的O'K:
SELECT event.name AS name, count( * ) num_attendee ,amount
FROM attendee
RIGHT JOIN event on event.id = attendee.event_id
LEFT OUTER JOIN(
SELECT event_id,amount=SUM(Amount)
FROM Gifts
GROUP BY event_id
) Gifts ON Gifts.event_id=event.id
WHERE event.company_id =6
GROUP BY event.name,amount