过滤数据库中的记录

问题描述 投票:-5回答:1

[enter image description here我有一个包含3列ID,单位和过程的表:

|Id  |Unit  |Process   |
|----|------|----------|
|100 |1     |0         |
|100 |0     |5         |
|101 |1     |0         |

输出

|Id  |Unit  |Process   |
|----|------|----------|
|101 |1     |0         |

我想排除过程值为5的所有ID。

因此ID 100具有进程5,因此ID 100的所有行都将被删除另外,我希望附加条件,所有记录在输出集中的单位值应为1。

这里是我尝试过的,但我需要简短的查询

Select id,unit, process from table a where id in
(
Select distinct id from table a where unit=1
)
And id not in
(
Select distinct id from table a where process=5
)
sql sql-server sql-server-2012 ssms
1个回答
0
投票

您正在寻找WHERE NOT EXISTS

数据设置:

CREATE TABLE mytable(
   Id      INTEGER  NOT NULL
  ,Unit    INTEGER  NOT NULL
  ,Process INTEGER  NOT NULL
);
INSERT INTO mytable(Id,Unit,Process) VALUES (100,1,0);
INSERT INTO mytable(Id,Unit,Process) VALUES (100,0,5);
INSERT INTO mytable(Id,Unit,Process) VALUES (101,1,0);

查询:

SELECT 
  *
FROM mytable AS m1
WHERE 
  m1.Unit = 1
  AND
  NOT EXISTS (SELECT 1 
              FROM mytable AS m2 
              WHERE m1.ID = m2.ID AND m2.Process = 5);

结果:

+-----+------+---------+
| Id  | Unit | Process |
+-----+------+---------+
| 101 |   1  |       0 |
+-----+------+---------+

0
投票

您可以使用EXISTS而不是EXISTS,这样,您将能够返回成功ID的所有记录:

;with tableA as
(select 100 as id,1 as unit,5 as Process union
select 100,0,5 union
select 101,1,0)

Select * from tableA a
where EXISTS
      (Select 1 from tableA b where a.id=b.id and b.unit=1) 
      AND NOT EXISTS
      (Select 1 from tableA c where a.id=c.id and c.process=5)
© www.soinside.com 2019 - 2024. All rights reserved.