【问题标题】:Left join exclude with multiple constraints具有多个约束的左连接排除
【发布时间】:2019-03-25 00:58:13
【问题描述】:

我试图隔离在任何一天只进行某种类型交易(现金、卡、支票)的客户。他们可能在某个日期进行了多次交易,但我想排除具有某种类型的交易。

我的交易表存储了客户编号、交易日期、交易类型、金额。如果唯一的交易(或交易)属于“卡”类型,我想查找客户和日期。

所以以下数据只会返回:3456, 26/03/2018

+---------+------------+------+--------+ |客户 |日期 |类型 |金额 | +---------+------------+------+--------+ |第1234章26/03/2018 |卡 | 10 | |第1234章26/03/2018 |现金 | 20 | |第1234章28/03/2018 |现金 | 20 | |第2345章26/03/2018 |现金 | 20 | |第2345章28/03/2018 |现金 | 20 | | 3456 | 26/03/2018 |卡 | 10 | | 3456 | 26/03/2018 |卡 | 20 | +---------+------------+------+--------+

这是我的代码,但它只返回空白行。

select t1.customer, t1.date
from transaction t1 
left join transaction t2 on t1.customer = t2.customer  
and t1.date = t2.date  
where t1.type = 'card' and t2.type <> 'card'  
and (t2.customer is null  and t2.date is null)  group by t1.customer, t1.date

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    我建议聚合和having:

    select t.customer, t.date
    from transaction t 
    group by t.customer, t.date
    having min(t.type) = max(t.type) and min(t.type) = 'card';
    

    Here 是一个 dbfiddle,说明它可以工作。

    【讨论】:

    • 对不起,这仍然没有返回任何内容。
    • @Goolsy 。 . .我不知道它对你没有任何回报。它会准确返回您为问题中的数据指定的内容:dbfiddle.uk/…
    • 我很抱歉。你是对的。我按场景进行了简化,然后错误地扩展了您的建议。我现在可以工作了。谢谢。
    猜你喜欢
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多