4

我有 postgresql 表,其值如下:

Table region_data:

region_name | population | region_code
------------+------------+-------------
Region 1    | 120000     | A
Region 2    | 200000     | A
Region 3    | -1         | B
Region 4    | -2         | -1

某些数据可能不可用(即 -1 和 -2 值)

以及包含这些值的翻译的表:

Table data_codes:

code  | meaning
------+-----------------------
-1    | 'Data not available'
-2    | 'Insufficient data'
...

Table region_types:

type  | meaning
------+---------------
A     | Mountain
B     | Grassland
...

我想做一个查询(实际上是一个视图),它返回 data_code 和 region_types 表提供的人类可读的翻译。例如,视图将返回:

Region Name | Population         | Region Type
------------+--------------------+-------------
Region 1    | 120000             | Mountain
Region 2    | 200000             | Mountain
Region 3    | Data Not Available | Grassland
Region 4    | Insufficient Data  | Data Not Available

我试过做一些子查询,但它们返回了很多重复的行,其中代码与 data_code 表中的任何内容都不匹配。

请帮忙?谢谢!

4

3 回答 3

1

假设数据代码和区域代码之间没有冲突,那么我看到了两个挑战。一是population列上的数据类型问题(值是整数但数据含义需要字符串)。另一种是将区域代码与数据代码相结合:

select rd.region_name,
       (case when population >= 0 cast(population as varchar(255))
             else p.meaning
        end) as population,
       r.meaning
from region_data rd left outer join
     (select type, meaning from region_types
      union all
      select code, meaning from data_codes
     ) r
     on rd.region_code = r.type left outer join
     data_codes p
     on rd.population < 0 and rd.population = p.code;
于 2013-09-06T20:47:03.873 回答
1
select
    r.region_name,
    coalesce(d1.meaning, r.population::text) as population,
    coalesce(d2.meaning, rt.meaning, r.region_code) as region_code
from region_data as r
    left outer join data_codes as d1 on d1.code = r.population
    left outer join data_codes as d2 on d2.code::text = r.region_code
    left outer join region_types as rt on rt.type = r.region_code
order by r.region_name

=> sql 小提琴演示

于 2013-09-06T21:01:09.297 回答
0

也许您可以发布查询。使用连接时重复的行通常意味着 INNER JOIN 而不是 LEFT JOIN

于 2013-09-06T20:46:40.930 回答