+----+--------+-----------+
| ID | ID_DEP | OPERATION |
+----+--------+-----------+
| 1 | 2 | T1 |
| 2 | 2 | T1 |
| 3 | 2 | T4 |
| 4 | 1 | T1 |
| 5 | 1 | T1 |
| 6 | 1 | T4 |
| 7 | 4 | T6 |
| 8 | 3 | T1 |
| 9 | 3 | T1 |
| 10 | 5 | T9 |
+----+--------+-----------+
嘿伙计们,帮我解决这个简单的问题。
如何仅从操作列中选择仅具有T1的ID(ID_DEP)而不是其他值。
答案 0 :(得分:0)
我会使用WHERE NOT EXISTS
测试数据
IF OBJECT_ID('tempdb..#TestData') IS NOT NULL DROP TABLE #TestData
CREATE TABLE #TestData (ID int, ID_DEP int, OPERATION varchar(2))
INSERT INTO #TestData (ID, ID_DEP, OPERATION)
VALUES
(1,2,'T1')
,(2,2,'T1')
,(3,2,'T4')
,(4,1,'T1')
,(5,1,'T1')
,(6,1,'T4')
,(7,4,'T6')
,(8,3,'T1')
,(9,3,'T1')
,(10,5,'T9')
查询
SELECT
td.*
FROM #TestData td
WHERE NOT EXISTS (SELECT 1 FROM #TestData sub WHERE sub.OPERATION <> 'T1' AND td.ID_DEP = sub.ID_DEP)
输出
ID ID_DEP OPERATION
8 3 T1
9 3 T1
基本上,NOT EXISTS
会返回值IS NOT
'T1'的所有行。如果存在ID_DEP
,那么我们希望将其从结果集中排除。