SQL筛选器基于SQL查询

时间:2016-10-21 02:39:24

标签: sql postgresql

输入表格 - 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

需要获取记录的子集,以便startend只是dieselhybrid车辆都位于startend

在上述情况下,期望只有城市B符合条件并期望输出表格如下

输出表格

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

两步流程

  1. 获取dieselhybrid
  2. startend辆汽车的城市列表
  3. 仅使用#1
  4. 中的城市的记录对该表进行子集

    如下所示,需要有关起点的帮助。

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

1 个答案:

答案 0 :(得分:1)

嗯,嗯。 。 。如果我理解了这个问题,您可以使用CTE获取城市列表,然后使用它来解决您的问题:

with c as (
      select city
      from (select start as city, engine
            from t1
            union all
            select end, engine
            from t1
           )
      where engine in ('petrol', 'deisel')
      group by city
      having count(distinct engine) = 2
     )
select t1.*
from t1
where t1.start in (select city from c) and
      t1.end in (select city from c);