1

i have 2 tables suppose table_1 & table_2 table_1 has 56 columns and 1.2 million records my query is like

table_1 like

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  

i want all RollNumber (group by with 2nd and third column) from table_1 where any status is 0 but don't want students who also have status = 5(or other than 1)

i have tried this

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)

This is the inner most query of my qhole query
i have also tried EXCEPT clause
Both queries take too long to execute

Brainiac
  • 107
  • 3
  • 10

3 Answers3

1

You can use EXISTS in place of NOT IN. This will be faster as there will be a boolean comparison instead of string comparison.

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)
Mit Bhatt
  • 472
  • 2
  • 11
1

Try to use NOT EXISTS instead of 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
                                                           )
Jibin Balachandran
  • 3,381
  • 1
  • 24
  • 38
1

Starting with SQL Server 2008 you can use count() over() to count how many total rows in a given group have a certain value.

In this case you'll want to count the number of status <> 1 per group and to only select rows that belong to a group with a count of 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
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85