Mysql 检索用户ID在12月份但不是1月份进行交易的记录
我有下表,我想选择在12月份进行交易的每个用户id,但不是在1月份Mysql 检索用户ID在12月份但不是1月份进行交易的记录,mysql,sql,select,case,Mysql,Sql,Select,Case,我有下表,我想选择在12月份进行交易的每个用户id,但不是在1月份 User_Id |Month |Transaction_Id |Transaction_Amount ------------------------------------------------------------ 1 |Dec |50 |452.36 1 |Jan |51
User_Id |Month |Transaction_Id |Transaction_Amount
------------------------------------------------------------
1 |Dec |50 |452.36
1 |Jan |51 |963.2
3 |Dec |52 |499.3
4 |Jan |53 |156.85
1 |Dec |54 |145.63
3 |Dec |55 |20.99
执行查询时,该表应如下所示:
User_Id |Month |Transaction_Id |Transaction_Amount
------------------------------------------------------------
3 |Dec |52 |499.3
3 |Dec |55 |20.99
请注意,我需要使用一个高效的查询来过滤上述要求,因为这将应用于数千条记录 有几种方法: 使用不存在:
select * from yourtable t
where month = 'Dec'
and NOT EXISTS (
select null from yourtable t2
where t2.user_id = t.user_id
and t2.month = 'Jan')
不在()中使用
使用左联接:
select t.* from yourtable t
left join yourtable t2 on t2.user_id = t.user_id and t2.month = 'Jan'
where t.month = 'Dec'
and t2.user_id IS NULL
看,我不知道存在像SQLFiddle这样的东西。格雷西亚斯!
select t.* from yourtable t
left join yourtable t2 on t2.user_id = t.user_id and t2.month = 'Jan'
where t.month = 'Dec'
and t2.user_id IS NULL