显示两行相差一个但其他方面相同的行

时间:2013-10-20 01:07:52

标签: sql postgresql join union common-table-expression

我正在做一个数据库课程,我有一个问题似乎无法得到正确答案。

共有3个表格:

country(code, iso_abbreviation, name)
area(name, city, country_code, latitude, longitude, elevation)
attraction(name, type, city, country_name, latitude, longitude, elevation)

现在,问题是:在吸引区和区域表中都找到了区域。列表

(country_abbreviation, area_name, latitude, longitude, elevation)

对于海拔5000英尺以上的所有区域。由于区域和景点数据之间可能存在一些不一致,因此纬度,经度和海拔可能会有所不同。在这种情况下,显示数据的两种变体。

所以我想出了下面的查询,但是我不确定它是否正确配对它并且它也没有将数据分成两行,其中一个(latitude, longitude, elevation)元素是不同的。

SELECT country.iso_abbreviation as country_abbreviation, area.name as name, 
area.latitude, area.longitude, area.elevation
FROM area JOIN country on country.code = area.country_code
      JOIN attraction on area.name = attraction.name
WHERE area.elevation > 10000

UNION 

SELECT DISTINCT country.iso_abbreviation as country_abbreviation, area.name, 
attraction.latitude, attraction.longitude, attraction.elevation
FROM area JOIN country on country.code = area.state_code
      JOIN attraction on area.name = attraction.name
WHERE attraction.elevation > 10000 ORDER BY country_abbreviation
; 

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

这可以做你所描述的:

WITH cte AS (
   SELECT c.iso_abbreviation AS country_abbreviation
        , a.name, a.latitude, a.longitude, a.elevation
   FROM   area       a
   JOIN   country    c ON c.code = a.country_code
   WHERE  a.elevation > 5000
   )
SELECT * FROM cte
UNION
SELECT c.country_abbreviation
     , t.name, t.latitude, t.longitude, t.elevation
FROM   cte        c
JOIN   attraction t USING (name)     -- assuming name links area & attraction (?)
ORDER  BY country_abbreviation, name -- (?)

但老实说,表格布局以及你给出的任务似乎都不清楚。