使用子查询删除具有特定值的分组行

时间:2018-04-19 10:53:33

标签: sql sql-server

请参阅:

http://sqlfiddle.com/#!18/479d1

我有这些表格:

CREATE TABLE Item 
(
    OrderNo varchar(10),
    ItemNo varchar(10)
);

CREATE TABLE Order1 
(
    OrderNo varchar(10),
    Month varchar(10)
);

INSERT INTO Item (OrderNo, ItemNo)
VALUES ('111','222'), ('111','333'),
       ('333','444'), ('333','222'), ('333','555'),
       ('444','222'), ('444','555');

INSERT INTO Order1 (OrderNo, Month)
VALUES ('111','Feb'), ('333', 'Jan'), ('444', 'May');

我希望退回没有项目'555'的订单。我认为这将是一个子查询,但我似乎无法做到正确。

我试过了:

SELECT 
    O.[OrderNo],
    O.[Month],
    I.[ItemNo]
FROM 
    Order1 O
JOIN 
    Item I ON O.[OrderNo] = I.[OrderNo]
WHERE 
    O.[OrderNo] IN (SELECT I.[OrderNo]
                    FROM Item I
                    GROUP BY I.[OrderNo], I.[ItemNo]
                    HAVING I.[ItemNo] <> '555')

返回此结果:

| OrderNo | Month | ItemNo |
|---------|-------|--------|
|     111 |   Feb |    222 |
|     111 |   Feb |    333 |
|     333 |   Jan |    444 |
|     333 |   Jan |    222 |
|     333 |   Jan |    555 |
|     444 |   May |    222 |
|     444 |   May |    555 |

但在这种情况下,我想删除所有带有项'555'的订单,结果如下:

| OrderNo | Month | ItemNo |
|---------|-------|--------|
|     111 |   Feb |    222 |
|     111 |   Feb |    333 |

4 个答案:

答案 0 :(得分:1)

您只需要改变您的想法 - 您希望订单列表中的NOT为555。

SELECT 
O.[OrderNo],
O.[Month],
I.[ItemNo]
FROM Order1 O
JOIN Item I ON O.[OrderNo] = I.[OrderNo]
WHERE O.[OrderNo] NOT IN
( SELECT I.[OrderNo]
FROM Item I
WHERE I.[ItemNo] = '555')

http://sqlfiddle.com/#!18/479d1/20

答案 1 :(得分:1)

没有分组的简单子查询怎么样?只需将IN更改为NOT IN,将条件从<> '555'更改为= '555',然后删除分组:

SELECT O.[OrderNo], O.[Month], I.[ItemNo]
FROM Order1 O
INNER JOIN Item I ON O.[OrderNo] = I.[OrderNo]
WHERE O.[OrderNo] NOT IN (SELECT [OrderNo]
                          FROM Item
                          WHERE [ItemNo] = '555')

答案 2 :(得分:0)

只需使用not exists

select o.*
from order1 o
where not exists (select 1
                  from items i
                  where i.orderno = o.orderno and i.itemno = 555
                 );

如果您想要所有商品以及订单,可以join进入:

select o.*, i.itemno
from order1 o join
     items i
     on o.orderno = i.orderno
where not exists (select 1
                  from items i
                  where i.orderno = o.orderno and i.itemno = 555
                 );

答案 3 :(得分:0)

尝试简单的子查询。

Select a.OrderNo, a.Month, b.ItemNo 
From Order1 a  
Inner Join  Item b 
On b.OrderNo = a.OrderNo 
Where a.OrderNo  
Not In (Select OrderNo From Item Where Itemno = '555')