1

火车运营商:

| train_operator_id |  name  |  
------------------------------
| 1                 | Virgin |
| 2                 |  First |

旅程:

| journey_id | train_operator | train_type |
--------------------------------------------
| 1          | 2              | 2          |
| 2          | 2              | 1          |
| 3          | 1              | 3          |
| 4          | 1              | 2          |

火车类型:

| train_type_id | date_made  |
------------------------------
| 1             | 1999-02-15 |
| 2             | 2001-03-11 |
| 3             | 2000-12-05 |

您将如何编写查询来查找所有使用第二古老类型列车的列车运营商?

使用给定的模式,查询应该只使用 Virgin,因为它是唯一使用第二旧火车类型的火车运营商

4

3 回答 3

2

尝试这个:

select distinct train_operator from journeys 
    inner join (Select * from train_types order by date_made LIMIT 1 OFFSET 1) sectrain 
    on sectrain.train_type_id = journeys.train_type

你进入英国铁路网络是吗?我曾经在 Funkwerk IT 工作,后者又为 Network Rail 提供时间表规划软件……

于 2013-03-12T10:59:05.850 回答
2

在 pg 中使用窗口函数的强大功能非常容易

SELECT DISTINCT train_operator_id, 
                name 
FROM   (SELECT t.train_operator_id, 
               t.name, 
               Rank() OVER (ORDER BY tt.date_made) AS rank 
        FROM   train_operators AS t 
               JOIN journeys AS j 
                 ON j.train_operator = t.train_operator_id 
               JOIN train_types AS tt 
                 ON tt.train_type_id = j.train_type) AS q 
WHERE  rank = 2; 

http://sqlfiddle.com/#!12/98816/8

于 2013-03-12T11:11:36.123 回答
1
select to.name
from
    train_operators to
    inner join
    journeys j on to.train_operator_id = j.train_operator
where
    j.train_type = (
        select train_type_id
        from train_types
        order by date_made
        limit 1 offset 1
    )
于 2013-03-12T11:48:23.707 回答