2016-10-18 95 views
0

我試圖刪除列B ='S'的列A值的所有行。下面是一個例子,我可以用數據顯示:根據列值排除查詢結果中的行

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
SELECT * 
    FROM YourTable 
WHERE column_A IN (SELECT column_A FROM YourTable 
        EXCEPT 
        SELECT column_A FROM YourTable 
         WHERE column_B = 'S'); 
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 
0

我認爲你需要使用表-A,不表-B在子查詢的WHERE子句:

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 
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

相關問題