如果我有桌子
`account`, `account_contact`, `contact_event` and `event`
以下FK存在
`account_contact`: `account_id`,`contact_id`
`contact_event`: `contact_id`, `event_id`
如何查询总票数的帐户出席频率'链接到帐户和事件的所有联系人,以及该帐户联系人的不同事件数。
我有以下内容但JOIN导致第一个子查询返回具有相同值的重复Ticket's Sold
行。
SELECT a1.id,`Tickets Sold`, a2.`Distinct Events Attended` FROM
(SELECT a.id, count(*) `Tickets Sold`
FROM account a JOIN account_contact ac
ON ac.active = 1 AND a.id=ac.account_id
JOIN contact_event ce
ON ac.contact_id=ce.contact_id
JOIN event e
ON ce.event_id=e.id AND ce.role = 'Checked In'
WHERE e.date_start >= '2015-12-31' AND e.date_end < '2017-01-01'
GROUP BY a.id ) a1
LEFT JOIN
(SELECT a.id,count(*) `Distinct Events Attended`
FROM account a
JOIN account_contact ac
ON a.id=ac.account_id AND ac.active = 1
JOIN contact_event ce
ON ac.contact_id=ce.contact_id AND ce.role = 'Checked In'
JOIN event e
ON ce.event_id=e.id
WHERE e.date_start >= '2015-12-31' AND e.date_end < '2017-01-01'
GROUP BY ac.id ) a2
ON a1.id=a2.id
显示问题的示例输出:正如您所见,Distinct Events正在返回针对该特定事件销售给公司的门票数量,因此在示例中有8个事件已参加,
AccountId Tickets DistinctEvents
38110518 15 5
38110518 15 1
38110518 15 3
38110518 15 2
38110518 15 1
38110518 15 1
38110518 15 1
38110518 15 1
相反,我应该回来:
AccountID Tickets DistinctEvents
38110518 15 8
编辑:示例数据
SELECT id,name FROM account;
id name
100 Big Company
SELECT id,first_name FROM contact;
id first_name
200 John
800 Other
SELECT contact_id,event_id FROM contact_event;
contact_id event_id
200 300
200 500
800 300
SELECT account_id,contact_id FROM account_contact;
account_id contact_id
100 200
100 800
SELECT id,name FROM event;
id name
300 Big Event
500 Small Event
应该返回:
AccountID Tickets DistinctEvents
100 3 2
答案 0 :(得分:1)
试试这个:
select
a.account_id,
count(event_id) tickets,
count(distinct event_id) distinct_events
from account_contact a
inner join contact_event e
on a.contact_id = e.contact_id
group by a.account_id;