我有下面的表格
customerID | orderID | orderDate
----------------------------------
1 | 67 | 2015-12-15
1 | 66 | 2015-10-20
1 | 65 | 2015-1-7
2 | 64 | 2014-9-6
2 | 63 | 2014-7-8
3 | 62 | 2015-1-15我需要确定2014年和2015年12个月内至少有3个不同orderID的所有customerID
发布于 2016-03-17 09:03:18
嗯。你可以这样做:
select distinct customerId
from t
where 3 <= (select count(*)
from t t2
where t2.customerId = t.customerId and
t2.date >= t.date and
t2.date < date_add(t.date, interval 12 month)
);在(customerId, date)上建立索引将有助于提高性能。而且,您可能需要在子查询中使用count(distinct OrderId),但是考虑到您的示例数据,这似乎不是必需的。
发布于 2016-03-17 09:05:43
试试这个:
SELECT customerID, order_count FROM (SELECT customerID, COUNT(DISTINCT orderID) AS
order_count WHERE YEAR(orderDate) = 2014 GROUP BY customerID) AS
table_orders WHERE order_count >= 3您可以先更改WHERE子句,以便更改日期范围,我建议您采用一种方法来计算整个2014年
https://stackoverflow.com/questions/36049770
复制相似问题