Postrge:行到列

时间:2018-04-10 13:05:43

标签: postgresql

我的桌子上有几种语言的街道名称:

streetName(addressId uuid, languageCode text, name text);

值:

addressid                            |languagecode |name            |
-------------------------------------|-------------|----------------|
e5c8c25c-f21e-47df-9172-7f3c7e52d669 |cz           |streetName_1_cz |
e5c8c25c-f21e-47df-9172-7f3c7e52d669 |en           |streetName_1_en |
e5c8c25c-f21e-47df-9172-7f3c7e52d669 |fi           |streetName_1_fi |
e5c8c25c-f21e-47df-9172-7f3c7e52d669 |sv           |streetName_1_sv |
bff096cc-4d4d-4b2e-aac2-bdc6ab659a72 |fi           |streetName_2_fi |
bff096cc-4d4d-4b2e-aac2-bdc6ab659a72 |cz           |streetName_2_cz |

需要将cz,fi,en中的街道名称转换为列。 (正是这三种语言,即使表中有更多语言,也可能发生,这三种语言中的某些语言的价值就会丢失)。

所以预期的结果是:

addressid                            |streetNameCz    |streetNameEn    |streetNameFi    |
-------------------------------------|----------------|----------------|----------------|
e5c8c25c-f21e-47df-9172-7f3c7e52d669 |streetName_1_cz |streetName_1_en |streetName_1_fi |
bff096cc-4d4d-4b2e-aac2-bdc6ab659a72 |streetName_2_cz |                |streetName_2_fi |

应该怎么做? 我尝试使用crosstable,但它无法正常工作,因为某些语言缺少值, 所以我的结果如下:

addressid                            |streetNameCz    |streetNameEn    |streetNameFi    |
-------------------------------------|----------------|----------------|----------------|
e5c8c25c-f21e-47df-9172-7f3c7e52d669 |streetName_1_cz |streetName_1_en |streetName_1_fi |
bff096cc-4d4d-4b2e-aac2-bdc6ab659a72 |streetName_2_cz |streetName_2_fi |                |

这是不正确的: - (。

这是我使用的选择:

SELECT *
FROM crosstab(
  'select 
    "addressid"::uuid as rowid, 
    languagecode::text as attribute,
    name::text as value
from streetName
where languageCode in (''cz'', ''en'', ''fi'') 
order by 1, 2')
AS ct(row_name uuid, "streetNameCz" text, "streetNameEn" text, "streetNameFi" text);

感谢您的任何建议。

兰格。

1 个答案:

答案 0 :(得分:0)

如果你不想使用交叉表,你可以简单地进行聚合:

  SELECT addressid,
         MAX( CASE WHEN languagecode = 'cz' THEN name END ) as lng_cz,
         MAX( CASE WHEN languagecode = 'en' THEN name END ) as lng_en,
         MAX( CASE WHEN languagecode = 'fi' THEN name END ) as lng_fi
  FROM YourTable
  GROUP BY addressid