mysql - 检索 User_ID 在 12 月而非 1 月进行交易的记录

标签 mysql sql select case

我有下表,我想选择在 12 月而非 1 月进行过交易的每个 user_id。

    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')

使用 NOT IN()

select * from yourtable t
where month = 'Dec'
and user_id NOT IN (
    select t2.user_id from yourtable t2
    where 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

关于mysql - 检索 User_ID 在 12 月而非 1 月进行交易的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47521611/

相关文章:

python - 从数据库中收集数据,函数与类

mysql - 是否可以在 SQL 中的 SELECT 中合并?

mysql - 如何使用 MySQL 从新闻表中选择最近 6 个月

sql - 如何在 SQL Server 中创建和查询链接数据库服务器?

css - chrome 中选择选项元素中的额外填充

mysql - update select same where 子句更新记录的子集

mysql - Laravel 或Where 给出意想不到的结果

mysql - 在另一个过程中使用 mysql 获取诊断

java - Hibernate - 使用一个 hibernate 映射查询多个表

php - Codeigniter 使用事件记录选择自定义