仅选择每个line_number的所有值均为空的项目

问题描述 投票:1回答:2

我有一张类似于以下内容的表格:

| item_number | line_number |  value |
|-------------|-------------|--------|
|           1 |           1 | (null) |
|           1 |           2 |     10 |
|           1 |           3 | (null) |
|           2 |           1 | (null) |
|           2 |           2 | (null) |
|           2 |           3 | (null) |
|           3 |           1 |      5 |
|           3 |           2 | (null) |
|           3 |           3 | (null) |

有三个独特的项目(根据item_number),每个项目有三个line_number。我想返回每个valueline_number为null的所有项目。

对于此表,我将返回以下内容:

| item_number |
|-------------|
|           2 |

因为只有item_number = 2所有的line_numbervalue IS NULL

DDL

CREATE TABLE tbl_A (
  item_number INT,
  line_number INT,
  value       INT,
);

INSERT INTO tbl_A VALUES (1, 1, NULL), (1, 2, 10), (1, 3, NULL);
INSERT INTO tbl_A VALUES (2, 1, NULL), (2, 2, NULL), (2, 3, NULL);
INSERT INTO tbl_A VALUES (3, 1, 5), (3, 2, NULL), (3, 3, NULL);

CREATE TABLE tbl_B (
  item_number INT
);

INSERT INTO tbl_B VALUES (2);
sql sql-server tsql
2个回答
3
投票

这是你想要的?

SELECT  item_number
FROM    tbl_A
GROUP BY item_number
HAVING  COUNT(value) = 0

1
投票

使用not exists

select distinct item_number
from tbl_A
where not exists (select 1 from tbl_A a
                  where a.item_number = tbl_A.item_number
                  and value is not null)

使用not in

select distinct item_number
from tbl_A
where item_number not in (select distinct item_Number
                       from tbl_A where value is not null)
© www.soinside.com 2019 - 2024. All rights reserved.