仅选择每年有订单的客户的ID

时间:2017-11-17 09:21:00

标签: mysql group-by

不知何故,我收到错误的客户ID,我只想要自第一个订单日期起每年至少订购一次的ID。

orders

o_id   o_c_id   o_type    o_date
1345   13       TA        2015-01-01
7499   13       TA        2015-01-16
7521   15       GA        2015-01-08
7566   16       TA        2016-01-24
7654   15       FB        2016-01-28

customers

c_id   c_name    c_email
13     Trump     example@gmail.com          
14     Obama     example@gmail.com
15     Miguel    example@gmail.com
16     Dequavo   example@gmail.com

我的查询:

SELECT c_id, YEAR(o_date), c_email
FROM orders
WHERE YEAR(o_date) BETWEEN YEAR(MIN(o_date)) AND YEAR(CURDATE())
GROUP BY YEAR(o_date)
HAVING COUNT(c_id) > 0
ORDER BY c_id

1 个答案:

答案 0 :(得分:2)

作为室内问题,您只需要Customer ID我已经为您提供了您可能正在寻找的内容的示例。我可以随意更改查询,因为我只选择o_c_id,假设是Customer ID

SELECT 
  o_c_id
FROM
  orders
GROUP BY 
  o_c_id
HAVING 
  (MIN(YEAR(o_date)) + COUNT(DISTINCT(YEAR(o_date))) -1) = YEAR(NOW())

这应该会为您提供自第一个订单以来每年下订单的所有o_c_id的列表。