SQL分组查询问题;根据一个字段的值评估一组行

时间:2010-04-23 20:26:43

标签: sql row

我有桌面供应商部件,列出了我的所有零件及其供应商。具有多个供应商的零件在此表中具有多个记录。我正在尝试编写一个只返回partid的查询,以及没有分配默认供应商的部件供应商。

Partid      Vendor     Defaultflag
1           A          1
2           B          0
2           C          0
3           D          0
3           E          0
3           F          1
4           G          0

我想返回以下内容:

Partid      Vendor
2           B
2           C
4           G

我显然遇到了partid 3的问题,并且查询将其视为已分配默认供应商。

4 个答案:

答案 0 :(得分:4)

null-left-join方法:

SELECT vp0.Partid, vp0.Vendor
FROM VendorParts AS vp0
LEFT JOIN VendorParts AS vp1 ON vp1.Partid=vp0.Partid AND vp1.Defaultflag=1
WHERE vp1.Partid IS NULL

答案 1 :(得分:2)

您可以尝试类似

的内容
DECLARE @VendorParts TABLE(
        Partid INT,
        Vendor VARCHAR(10),
        Defaultflag INT
)
INSERT INTO @VendorParts SELECT  1,'A',1 
INSERT INTO @VendorParts SELECT  2,'B',0 
INSERT INTO @VendorParts SELECT  2,'C',0 
INSERT INTO @VendorParts SELECT  3,'D',0 
INSERT INTO @VendorParts SELECT  3,'E',0 
INSERT INTO @VendorParts SELECT  3,'F',1 
INSERT INTO @VendorParts SELECT  4,'G',0

SELECT *
FROM    @VendorParts vp
WHERE    NOT EXISTS (
                        SELECT  1 
                        FROM    @VendorParts 
                        WHERE   Partid = vp.Partid 
                        AND     Defaultflag = 1
                    )

输出

Partid      Vendor     Defaultflag
----------- ---------- -----------
2           B          0
2           C          0
4           G          0

答案 2 :(得分:1)

使用内部选择来查找没有默认供应商的部件。这是按MAX(Defaultflag)分组时partid = 0的部分。然后,您可以将其连接回原始表以获取所有行。这是完整的查询:

SELECT T2.Partid, T2.Vendor
FROM (
    SELECT Partid
    FROM Table1
    GROUP BY Partid
    HAVING MAX(Defaultflag) = 0
) T1
JOIN Table1 T2
ON T1.PartId = T2.PartId

结果:

2, 'B'
2, 'C'
4, 'G'

答案 3 :(得分:0)

类似

select 
 partid, 
 vendor 
from 
 vendorparts 
where 
 partid not in (
  select 
    partid 
   from 
    vendorparts 
   where 
    defaultflag = 1
 );