mysql - 查询选择仅在某一年购买的客户
问题描述
嗨,我有一张看起来像这样的桌子
我需要选择仅在 2015 年购买的客户,这意味着我不需要在 2015 年购买的客户,而 2016 年只需要仅在 2015 年购买的客户。但可悲的是,我想不出任何帮助都会得到满足
是否可以这样写
select customerid
from x
where year(date)="2015" and year(date)!=2016
谢谢你 :)
解决方案
您可以通过首先找到 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
推荐阅读
- java - 获取包含数字签名的pdf页面的页面索引
- powershell - 比较 .csv 并仅添加具有更新值的行
- hibernate - 如何在 Jboss EAP 6.2 中为 infinispan 2LC 启用 JMX 统计信息
- reactjs - 父组件重新渲染时如何强制 Apollo Query 组件重新运行查询
- json - Xamarin JSON 反序列化
- python - 根据给定日期获取日期名称
- python - 如何在python中读取隐藏的输出细节?
- android - 如何使用 AOSP 映像打包 3rd 方 .so
- java - Java PING 一个 IP 地址范围
- python - Z3Py 中的量词错误