2016-10-18 12 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 

ここからは、私は、列Bの「S」を示し、列A(100および102)からすべてのエントリを排除たいので、私はと残されています:

column A column B 
    101   P 
    101   C 
    103   C 
    104   P 

Iは、同様の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の例)。あなたのクエリ編集

select * 
from Table_A 
where Column_B != 'S' 
    and Column_A not in (
     select distinct column_A 
     from Table_A 
     where Column_B = 'S' 
     ) 

:私はあなたがwhere句であなたのサブクエリでTable_BないTable_Aを使用する必要があると思う

答えて

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

。これは動作するはずです:これは別の答えに非常に似て

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 INとは対照的に、NOT EXISTS使用することを除いて。 INキーワードは非常に便利ですが、パフォーマンス上の理由からusing NOT IN should be avoidedがあります。

関連する問題