如果一个键的所有记录都符合条件,如何返回一条记录?

时间:2018-05-07 18:58:32

标签: sql sql-server tsql

我正在寻找一种方法来处理以下场景。我有一个数据库表,只有当该文档的所有记录都符合条件时,我才需要返回一条记录。

我得到了这张桌子:

    Docnum  Qty
    220      1
    220      1
    220      1
    220     10
    221      1
    221      0
    221      0
    221     10
    222      1
    222      1
    222      1
    222     10

查询结果必须只返回所有数量不等于零的记录,在本例中为“docnum”220和222:

    Docnum
    220
    222

7 个答案:

答案 0 :(得分:4)

使用NOT IN

select distinct Docnum
from yourTable
where Docnum not in (select Docnum from yourTable where Qty = 0)

答案 1 :(得分:2)

您可以使用条件聚合:

SELECT docnum
FROM table
GROUP BY docnum
HAVING SUM(CASE WHEN Qty = 0 THEN 1 ELSE 0 END) = 0;

<强> DBFiddle Demo

答案 2 :(得分:2)

为什么不使用not exists

select distinct t.Docnum  
from table t
where not exists (select 1 from table where Docnum = t.Docnum and Qty = 0);

答案 3 :(得分:2)

select Docnum  
from MyTable
group by Docnum
having min(abs(Qty)) <> 0

SQL Fiddle

MS SQL Server 2017架构设置

CREATE TABLE MyTable
    ([Docnum] int, [Qty] int)
;

INSERT INTO MyTable
    ([Docnum], [Qty])
VALUES
    (220, 1),
    (220, 1),
    (220, 1),
    (220, 10),
    (221, 1),
    (221, 0),
    (221, 0),
    (221, 10),
    (222, 1),
    (222, 1),
    (222, 1),
    (222, 10)
;

查询1

select Docnum  
from MyTable
group by Docnum
having min(abs(Qty)) <> 0

<强> Results

| Docnum |
|--------|
|    220 |
|    222 |

答案 4 :(得分:1)

和第三种方法,因为其他两种方法也可以。

SELECT distinct docnum
FROM yourTable A
WHERE not exists (SELECT 1 
                  FROM yourtable B
                  WHERE B.qty=0
                    and A.DocNum = B.DocNum)

这使用相关子查询来标识所有文档,其中docNum的单个记录不包含0.它将受益于qty和docNum上的索引。

答案 5 :(得分:1)

假设Qty永远不会消极:

select Docnum
from tab
group by Docnum
Having min(Qty) > 0

如果它也可能是否定的:

select Docnum
from tab
group by Docnum
Having min(abs(Qty)) <> 0

答案 6 :(得分:-1)

您可以使用此查询:

select * from "table_name" where Qty <> 0;