如何选择所有超过3个并发优惠的客户?
我有的优惠表有这些专栏:
custid offerid inidate enddate title
12, 33, "2016-01-15" , "2016-01-30" , "offer 33"
12, 34, "2016-01-18" , "2016-01-22" , "offer 34"
12, 35, "2016-01-20" , "2016-01-30" , "offer 35"
12, 36, "2016-02-01" , "2016-02-30" , "offer 36"
106, 43, "2016-01-15" , "2016-01-30" , "offer 43"
106, 44, "2016-01-18" , "2016-01-22" , "offer 44"
106, 45, "2016-01-20" , "2016-01-30" , "offer 45"
106, 46, "2016-01-01" , "2016-02-30" , "offer 46"
客户12的并发优惠少于4个,但客户106拥有4个并发优惠 - 从20日到22日将是4个并发报价
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 01 02 03 04 05
33 12 |--------------------------------------------|
34 12 |-----------|
35 12 |------------------------------|
36 12 |---------------
43 106 |--------------------------------------------|
44 106 |-----------|
45 106 |------------------------------|
56 106 |-----------------------------------------------------------------
^^^^^^^^
106 has 4 concurrent offers
答案 0 :(得分:0)
select custid, count(offerid) from offer group by custid having count(offerid) > 3
答案 1 :(得分:0)
要获取客户的优惠计数,请使用此查询。
select count(offerid) from offer where custid = ?;
或列出所有至少有4个优惠的客户:
select distinct o1.custid from offer o1 where (select count(o2.offerid) from offer o2 where o1.custid = o2.custid) > 3;
如果您还想检查重叠的日期间隔,请将其添加到select count()查询中:
select distinct o1.custid from offer o1 where
(select count(o2.offerid) from offer o2 where
o1.custid = o2.custid
and o1.start_date <= o2.end_date
and o1.end_date >= o2.start_date) > 3;
答案 2 :(得分:0)
Select custid, count(*) as numOfOrders from offer
where NOW() between inidate and enddate
group by custid
having numOfOrders > 3
答案 3 :(得分:0)
E.g。
SELECT x.customer_id
FROM my_table x
JOIN my_table y
ON y.customer_id = x.customer_id
AND y.start_date <= x.end_date
AND y.end_date >= x.start_date
AND y.offer_id >= x.offer_id
GROUP
BY x.offer_id
HAVING COUNT(*) >= 4;