【发布时间】: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