我试图删除列B中所有行的值,其中列B =' S'。这是我可以用数据显示的一个例子:
column A column B
100 S
100 P
100 C
101 P
101 C
102 S
103 C
104 P
从这里开始,我要删除A列中显示' S'的所有条目。在B栏(100和102)中,我留下了:
column A column B
101 P
101 C
103 C
104 P
我试图按照类似的SO帖子(Exclude rows with a column containing a value if multiple rows exist for)中的步骤进行操作,但它仍然排除了' S'存在并保持共享列A值。
例如,我在查询的相关部分是:
select table_a.column_a
,table_b.column_b
,...
from table_z
inner join table_b
on table_z.z = table_b.z
inner join table_y
on table_z.y = table_y.y
left outer join table_a
on table_x.x = table_a.x
where date > 'YYYY-MM-DD'
and (
table_b.column_b not in (
select column_b
from table_b
where (column_b = 'S')
)
)
order by table_a.column_a
但它只删除了column_b =' S'并且不会删除column_A值与column_b出现位置匹配的行(本帖子开头的column_a = 100示例)。
答案 0 :(得分:1)
Declare @YourTable table (ColumnA int,ColumnB varchar(25))
Insert Into @YourTable values
(100,'S'),
(100,'P'),
(100,'C'),
(101,'P'),
(101,'C'),
(102,'S'),
(103,'C'),
(104,'P')
Select *
From @YourTable
Where ColumnA Not In (Select Distinct ColumnA From @YourTable where ColumnB='S')
返回
ColumnA ColumnB
101 P
101 C
103 C
104 P
答案 1 :(得分:0)
我认为您需要在where子句中的子查询中使用Table_A而不是Table_B:
select *
from Table_A
where Column_B != 'S'
and Column_A not in (
select distinct column_A
from Table_A
where Column_B = 'S'
)
修改了您的查询。这应该有效:
select table_a.column_a
,table_b.column_b
,...
from table_z
inner join table_b
on table_z.z = table_b.z
inner join table_y
on table_z.y = table_y.y
left outer join table_a
on table_x.x = table_a.x
where date > 'YYYY-MM-DD'
and table_a.column_b != 'S'
and table_a.column_A not in (
select distinct table_a.column_A
from Table_A
where Column_B = 'S'
)
order by table_a.column_a
答案 2 :(得分:0)
SELECT *
FROM Table_A as A
WHERE NOT EXISTS (
SELECT *
FROM Table_B as B
WHERE B.ColumnA = A.ColumnA
AND B.ColumnB = 'S' )
这与另一个答案非常相似,只是它使用NOT EXISTS而不是NOT IN。 IN关键字非常有用,但出于可能的性能原因using NOT IN should be avoided。
答案 3 :(得分:0)
SELECT *
FROM YourTable
WHERE column_A IN ( SELECT column_A FROM YourTable
EXCEPT
SELECT column_A FROM YourTable
WHERE column_B = 'S' );