我想使用MySQL进行查询,以查找过去3年(2016年至2019年)每年至少订购或下载一次的客户。但是,他们必须对订购或下载的那些物品留下反馈。
因此,我必须使用以下表格:反馈,FAV(代表免费的年度视频)和下载,以及Contact(包含所有用户信息)
SELECT c.id, c.FirstName, c.LastName
FROM contact c
JOIN download_counts dl
on c.Id = dl.ContactId
JOIN freeannualvideo f
on c.Id = f.ContactId
INNER JOIN (select fb.ItemId
from feedback fb
group by fb.ItemId) FBExistFAV
ON FBExistFAV.ItemId = f.ItemId
INNER JOIN (select fb.ItemId
from feedback fb
group by fb.ItemId) FBExistDL
ON FBExistDL.ItemId = dl.ItemId
WHERE
EXISTS (select 1 from download_counts dl where c.id = dl.ContactId and dl.DateAdded between '2016-06-30' and '2017-06-30')
AND EXISTS (select 1 from download_counts dl where c.id = dl.ContactId and dl.DateAdded between '2017-07-01' and '2018-06-30')
AND EXISTS (select 1 from download_counts dl where c.id = dl.ContactId and dl.DateAdded between '2018-07-01' and '2019-04-27')
OR
(EXISTS (select 1 from freeannualvideo f where c.id = f.ContactId and f.DateAdded between '2016-06-30' and '2017-06-30')
AND EXISTS (select 1 from freeannualvideo f where c.id = f.ContactId and f.DateAdded between '2017-07-01' and '2018-06-30')
AND EXISTS (select 1 from freeannualvideo f where c.id = f.ContactId and f.DateAdded between '2018-07-01' and '2019-04-27'))
GROUP BY c.Id;
因此,联系人必须在2017、2018和2019 PLUS至少拥有一个DL或FAV,他们每年需要为其中一个DL或FAV提供反馈
很好的例子:(应该拉)
约翰·史密斯
2017年有DL或FAV且左反馈
2018年有DL或FAV且有左反馈
2019年有DL或FAV且有左反馈
错误的例子:(不应该被拉)
杰克·约翰逊
2017年有DL或FAV且左反馈
2018年出现DL或FAV并留下否反馈
2019年有DL或FAV且有左反馈