SQL Filter based on results from SQL query
21:56 20 Oct 2016

Input table - t1

make   | model | engine | kms_covered  | start   | end
-------------------------------------------------------
suzuki | sx4   | petrol | 11           | City A  | City D
suzuki | sx4   | diesel | 150          | City B  | City C
suzuki | swift | petrol | 140          | City C  | City B
suzuki | swift | diesel | 18           | City D  | City A
toyota | prius | petrol | 16           | City E  | City A
toyota | prius | hybrid | 250          | City B  | City E

I need to get a subset of the records such that start and end is only cities where both diesel and hybrid cars were either in start or end.

In above case, expect that only city B qualifies for the condition and expect output table as below

output table

make   | model | engine | kms_covered  | start   | end
-------------------------------------------------------
suzuki | sx4   | diesel | 150          | City B  | City C
suzuki | swift | petrol | 140          | City C  | City B
toyota | prius | hybrid | 250          | City B  | City E

Two step process:

  1. Get list of cities where both diesel and hybrid cars have either in start or end
  2. Subset the table with only records having cities in #1

Here is my starting point:

select * from t1
 where start in () or end in ()
sql postgresql