简体   繁体   中英

Select Query to get data that matches and do not matches the where condition in SQL

  • If there is a total of 1000 records in a table
  • I need to get total of 500 rows that matches multiple conditions
  • out of N conditions one Condition(A) is like an optional condition
  • if there are only 50 records that matches all the N conditions and 600 records that matches all N-1 conditions (except A)
  • then i need to get an composite of 50 + (450 records out of 600 records) as a 500 records from SQL
  • Usage of LEFT JOIN is not intended as we have a table with high volume of data

Example:

在此处输入图片说明

  • From the above table i need to get 4 Id's that matches Course B.Tech and age above 25
  • The course table is an optional Condition so i need to get ids 1,2,3,5,6 as an result
  • From this 6 rows i need to get 5 records in which i cannot elimnate id 5 as it matches all conditions instead i can eliminate any one record apart from this as other records matches only one condition

You add this condition to a case expression in the order by clause and thus make sure you get these records first:

SELECT    TOP 500 *
FROM      mytable
WHERE     /* conditions */
ORDER BY  CASE WHEN /* optional condition */ THEN 0 ELSE 1 END

You can try the following query using union clause

create table #temp (id int, Age int, Course varchar(20))
insert into #temp values (1, 25, 'BE'),(2, 30, 'BE'),(3, 40, 'BE'),(4, 22, 'BE'),(5, 25, 'B. Tech'),(6, 27, 'BE')

select Top 4 * from #temp
where age >= 25 
union
select * from #temp
where (Course is null or Course = 'B. Tech')
union
select * from #temp
where age >= 25 OR (Course is null or Course = 'B. Tech')

The output is as shown below

id  Age Course
1   25  BE
2   30  BE
3   40  BE
5   25  B. Tech
6   27  BE

You can find the live domo here- Demo Data Matches

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM