微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

不仅显示重印数据,还显示非打印数据?使用左连接

如何解决不仅显示重印数据,还显示非打印数据?使用左连接

select
    barcode,fullname,social,printdate,(case
        when min(orderId) = 0 then 'yes'
        when min(orderid) <> 0 then 'No'
    end) as Reprint
from
    clientdata (nolock)
left outer join ReprintTable with(nolock) on
    Code = barcode
where
    clientcode = '334556'
    --and printdate < '2021-02-23'

    group by barcode,printdate
order by
    printdate

这个查询背后的逻辑:

所以基本上我想显示所有重印卡和非重印卡,我使用左外连接加入重印表(存储重印卡的所有信息,如重印日期)

基本上如果卡片的orderid为0,则表示卡片已重印,反之亦然。

我想让我的查询显示所有未重印的卡片并排除在 23 日之前重印的重印卡片,但是一旦我在其中添加and 子句,非重印卡片就不再显示.

我该如何解决这个问题。

如果我重新添加 and 子句的输出(不是真实数据,而是使用示例):

barcode     fullname        Social   PrintDate          Reprint
024556      Donald Wick     4556     2021-01-03         yes
024557      John Trump      4558     2021-01-08         yes

如果我去掉 and 子句:

barcode     fullname        Social   PrintDate          Reprint
024556      Donald Wick     4556     2021-01-03         yes
024557      John Trump      4558     2021-01-08         yes
024557      Stop gambling   4556     null               no

等等...

无论如何,我可以将非重印数据与过滤后的重印范围一起显示吗?

解决方法

您需要包含 printdate 为 null 的情况 - 即 ReprintTable 表中不存在记录时。

如果你为你的表设置别名并用表别名作为列的前缀,事情就会变得更加清晰。

另请注意,由于某些 PrintDate 值为空,因此它的顺序可能与您预期的不同。

select barcode,fullname,Social,RT.PrintDate,(
        case when min(orderId) = 0 then 'yes'
        when min(orderid) <> 0 then 'No'    
        end
    ) as Reprint 
from ClientData CD with (nolock)
left outer join ReprintTable RT with (nolock) on Code = barcode
where clientcode = '334556'
and (RT.PrintDate is null or RT.PrintDate < '2021-02-23')
group by barcode,RT.printdate
order by RT.PrintDate

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。