首页 > 解决方案 > 查询选择仅在某一年购买的客户

问题描述

嗨,我有一张看起来像这样的桌子

桌子

我需要选择仅在 2015 年购买的客户,这意味着我不需要在 2015 年购买的客户,而 2016 年只需要仅在 2015 年购买的客户。但可悲的是,我想不出任何帮助都会得到满足

是否可以这样写

     select customerid
      from x 
      where year(date)="2015" and year(date)!=2016

谢谢你 :)

标签: mysqlselect

解决方案


您可以通过首先找到 2016 年购买的客户,然后获取所有 2015 年购买的客户,除了那些也在 2016 年组中列出的客户:

SELECT DISTINCT t1.customerid
FROM x AS t1
LEFT JOIN (
    SELECT DISTINCT customerid -- select the 2016 consumerid group
    FROM x
    WHERE date BETWEEN '2016-01-01' AND '2016-12-31'
) AS t2
ON t1.customerid = t2.customerid
WHERE date BETWEEN '2015-01-01' AND '2015-12-31'
AND t2.customerid IS NULL -- only take rows without consumerid match in 2016

我还添加DISTINCT以避免重复(如果客户在 2015 年购买了多次)

正如@Strawberry 提到的,year(date)不能使用索引,所以我将其更改为BETWEEN


推荐阅读