Postgresql:" CASE"基于另一个表

时间:2017-08-08 08:53:57

标签: sql postgresql

我有两个表:stops_jena,其中有停靠点(每个停靠点只出现一次)和trips_clean,其中有相同的停靠点,但很多次。还有一个名为vehicle的列,其中包含三个不同的值。 对于每个站点,如果此站点的车辆是“公共汽车”,我想要一个列true的列。

picture of stops_jena

WITH trips_stops_bus as (
  SELECT DISTINCT stop_name as stop
    FROM hafas.trips_clean
    WHERE hafas.trips_clean.vehicle = 'bus'
)

SELECT
    DISTINCT stops_jena.stop_name,
    case when stops_jena.stop_name = trips_stops_bus.stop then 'true' else 'false' end as bus   
FROM hafas.stops_jena, trips_stops_bus
ORDER BY stops_jena.stop_name 

这是我的查询,但它会停止两次列总线为真look here

1 个答案:

答案 0 :(得分:0)

我使用了IN-conditon,因此止损只出现一次:

 WITH trips_stops_bus as (
SELECT DISTINCT stop_name as stop
FROM hafas.trips_clean
WHERE hafas.trips_clean.vehicle = 'bus'
    )

SELECT
    DISTINCT stops_jena.stop_name,
    case when stops_jena.stop_name IN (SELECT stop from trips_stops_bus) then 'true' else 'false' end as bus 'false' end as bus   
FROM hafas.stops_jena, trips_stops_bus
ORDER BY stops_jena.stop_name