【问题标题】:Show not only the reprint data but also non-printed one? Using left join不仅显示转载数据,还显示未打印的数据?使用左连接
【发布时间】:2021-05-26 08:06:00
【问题描述】:
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

这个查询背后的逻辑:

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

基本上如果card的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 是否偶然属于ReprintTable 表?仅供参考...我希望您知道在所有地方使用 nolock 的后果 - 不建议这样做。
  • 是的printdate属于转载表
  • 嘿,它成功了。谢谢!那是一个错字
  • 旁白:如果orderId 不可为空,那么您的case 表达式可以简化为:case when min( orderId ) = 0 then 'yes' else 'No' end as Reprint。它要么为零,要么不为零(如果您排除了is NULL)。

标签: sql sql-server tsql outer-join


【解决方案1】:

您需要包含printdate 为空的情况——即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

【讨论】:

    猜你喜欢
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    相关资源
    最近更新 更多