2017-02-23 5 views
1

との時間を取っている私は、2つのテーブルを想定していのtable_1 & table_2 のtable_1は56列と120万件のレコードを持っている 私のクエリは、私が欲しいSQLないが、同様のテーブル

よう

のtable_1

RollNumber | Subject | G   | Part | Status 
------------------------------------------------ 
1   | 1  | 1   | 1 | 1 
1   | 1  | 1   | 2 | 1 
1   | 2  | 1   | 1 | 1 
1   | 2  | 1   | 2 | 5 
1   | 3  | 1   | 1 | 0 
1   | 3  | 1   | 2 | 1 
2   | 1  | 2   | 1 | 1 
2   | 1  | 2   | 2 | 1 
2   | 2  | 2   | 1 | 1 
2   | 2  | 2   | 2 | 1 
2   | 3  | 2   | 1 | 1 
2   | 3  | 2   | 2 | 1 
3   | 1  | 2   | 1 | 1 
3   | 1  | 2   | 2 | 1 
3   | 2  | 2   | 1 | 1 
3   | 2  | 2   | 2 | 1 
3   | 3  | 2   | 1 | 0 
3   | 3  | 2   | 2 | 1 

のようなものですすべてのステータスが0であるが、ステータス= 5(または1以外)の生徒を望んでいないtable_1のすべてのRollNumber(2番目と3番目の列でグループ化)

これを試してみました

select * from table_1 as t1 
inner join table_2 as t2 
on t1.column2 = t2.column2 and t1.column3 = t2.column3 and t1.column4 = t2.column4 
where t1.column1 not in 
    (select column1 from table_1 where status = 5) 

これは、私はまた、あなたがNOT IN.この意志の代わりにEXISTSを使用することができます
両方のクエリが

+0

なぜ 'status'をフィルタリングするためにサブクエリを使用しますか? –

+1

[実行計画](http://stackoverflow.com/questions/7359702/how-do-i-obtain-a-query-execution-plan)のクエリを表示してください。 'column1'、' column2'、 'column3'、' status'にインデックスを追加しましたか? – kennytm

+0

@kennytm私は編集した質問を今すぐに検討してください,,,ありがとう – Brainiac

答えて

1

を実行に時間がかかりすぎる句EXCEPT を試してみました
私qholeクエリの最も内側のクエリですstringの比較の代わりにbooleanの比較があるため、高速にする必要があります。

select * from table_1 as t1 
inner join table_2 as t2 
on t1.column1 = t2.column1 and t1.column2 = t2.column2 and t1.column3 = t2.column3 
where not EXISTS 
    (select 1 from table_1 where status = 5 and t1.column3 = table_1.column3) 
1

あなたが与えられたグループ内の総行が特定の値を持っているどのように多くカウントするcount() over()を使用することができますSQL Server 2008のを皮切り代わりNOT IN

SELECT * 
FROM table_1 AS t1 
INNER JOIN table_2 AS t2 
ON t1.column1 = t2.column1 AND t1.column2 = t2.column2 AND t1.column3 = t2.column3 
WHERE NOT EXISTS(
        SELECT 1 
        FROM table_1 
        WHERE status=5 AND column3=t1.column3 
                  ) 
1

NOT EXISTSを使用してみてください。

この場合、グループごとにstatus <> 1の数を数え、数が0のグループに属する行のみを選択することをお勧めします。

select * from (
    select * , 
     count(case when status <> 1 then 1 end) over(partition by RollNumber, G) c 
    from table_1 
) t where c = 0 
+0

これは動作していますが、問題はC#でLINQに変換する必要があります、ありがとうございました – Brainiac

+0

LINQにクエリを変換する助けが必要な場合は、新しい質問を開きます:) – FuzzyTree

+0

私はこのクエリもmysqlのためにしたい – Brainiac

関連する問題