我有一个用于跟踪Bin数据库的PartNumber信息的表。每个Bin可以有许多Partnumbers但至少有一个PartNumber必须标记为该Bin的Primary。在我的PartNumbers表中,有许多记录从未被识别为主要记录,我需要能够识别它们,以便在能够强制执行业务规则之前清除数据。我看过OVER(PARTION BY),但我无法弄清楚如何获得那些没有至少一个标记为主要的PartNumber的记录。
表结构:
PartNumbnerID PK int(IDENTITY)
PartNumber varchar(20)
BinNumber char(5) FK
BinPrimary bit
示例数据:
PartNumberID PartNumber BinNumber BinPrimary
1 123 22222 0
2 345 22222 0
3 456 33333 0
4 678 33333 0
5 789 44444 1
6 890 44444 0
查询结果如下:
BinNumber
22222
33333
答案 0 :(得分:2)
这很简单:
select BinNumber
from MyTable
group by BinNumber
having max([Primary]) = 0
这是一个SqlFiddle:http://www.sqlfiddle.com/#!3/c1d25/2
答案 1 :(得分:1)
当您需要更多列时,这可能是一个优势,但是如果您只需要Vin Number,那么您应该使用Wolf的解决方案
SELECT PartNumberID,PartNumber,BinNumber,Primary FROM
(
SELECT
PartNumberID,PartNumber,BinNumber,Primary,
max(primary) over(partition by BinNumber) chk
FROM table
) a
WHERE chk = 0