-1
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,
    fullname,
    social,
    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

ETC...

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

4

1 回答 1

0

您需要包括printdatenull 时的情况 - 这将是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, fullname, Social, RT.printdate
order by RT.PrintDate
于 2021-02-24T02:01:56.570 回答