简体   繁体   English

基于SQL查询结果的SQL筛选器

[英]SQL Filter based on results from SQL query

Input table - t1 输入表-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

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 . 需要获取记录的子集,以使startend仅是dieselhybrid汽车均处于startend

In above case, expect that only city B qualifies for the condition and expect output table as below 在上述情况下,期望只有城市B符合条件,并且期望输出表如下

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 获取dieselhybrid汽车startend的城市清单
  2. Subset the table with only records having cities in #1 用仅在#1中具有城市的记录对表进行分组

Need help with starting point as below. 在以下方面需要帮助。

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

Hmmmm . 嗯。 . . If I understand the question, you can get the list of cities using a CTE and then use this in to solve your question: 如果我理解这个问题,则可以使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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