关于sql case when 函数条件筛选的妙用

mysql case when函数妙用

现有如下一张表格:lianxi,需要提取出10月份无购买行为且 7、8、9月有购买行为的会员编号

会员编号 购买日期
1 2019-07-18 00:00:00
1 2019-07-22 00:00:00
1 2019-07-11 00:00:00
2 2019-08-30 00:00:00
2 2019-10-15 00:00:00
2 2019-07-14 00:00:00
3 2019-07-01 00:00:00
3 2019-09-20 00:00:00
3 2019-08-11 00:00:00
4 2019-10-01 00:00:00
4 2019-10-04 00:00:00
4 2019-07-12 00:00:00
5 2019-08-01 00:00:00
5 2019-08-31 00:00:00
5 2019-09-25 00:00:00

基于这个产出逻辑需要用到case when函数,先简单介绍一下case when 函数,可以简单理解为条件判断并且赋值的一个函数:一个case when过程包含case when then else end
when:条件判断
then:符合when条件的赋予所需要的值
else:不符合then中条件所赋予的值
end:表示case when 过程的结束
首先我们需要新增两列:
列1:10月份是否有消费(0,1表示,1代表有消费)
列2:7、8、9月份是否有消费(0,1表示,1代表有消费)

SELECT 
`会员编号`,
case when `消费日期` between '2019-07-01' and '2019-09-30' then 1 else 0 end "m7_m9",
case when `消费日期` between '2019-10-01' and '2019-10-31' then 1 else 0 end "m10"
from lianxi

结果如下
关于sql case when 函数条件筛选的妙用_第1张图片
然后按会员编号分组看新列的最大值,如果为1说明他们在当月有购买行为,如果为0说明在当前条件月无购买行为,按最大值来判断需求所需人员,具体代码如下:

select `会员编号` 
FROM
(SELECT `会员编号`,
case when `消费日期` between '2019-07-01' and '2019-09-30' then 1 else 0 end "m7_m9",
case when `消费日期` between '2019-10-01' and '2019-10-31' then 1 else 0 end "m10"
from lianxi) a
GROUP BY `会员编号`
having max(a.`m7_m9`)=1
and MAX(a.`m10`)=0

结果如图所示
关于sql case when 函数条件筛选的妙用_第2张图片
这样就完成啦~

PS:新人第一次发帖,还请多多关照~

你可能感兴趣的:(mysql)