Postgresql 将多行组合成多列

Postgresql combine multiple rows into multiple columns

我关注sql:

with modules as (
    select *
    from translate_dev.tab_module as m
             join translate_dev.tab_translation_module as tm on m.id = tm.module_id
)
select tm.name,
       t.id,
       t.language_id,
       t.text
from translate_dev.tab_translation as t
         join modules as tm on tm.translation_id = t.id
        
where t.id in (
               1166615, 1166401, 1166578, 1166579, 1166580, 1166581, 1166582, 1166583, 1166584, 1166586, 1166587,
               1166588, 1166589, 1166591, 1166595, 1166597, 1166598, 1166599, 1166600, 1166601, 1166602, 1166603,
               1166604, 1166605, 1166606, 1166607, 1166608, 1166610, 1166612, 1166614, 1166616, 1166617, 1166618,
               1166619, 1166621, 1166623, 1166624, 1166626, 1166627, 1166628, 1166629, 1166631, 1166632, 1166633,
               1166634, 1166635, 1166636, 1166637, 1166638, 1166640, 1166641, 1166642, 1166643, 1166644, 1166645,
               1166646, 1166650, 1166651, 1166652, 1166653, 1166654, 1166655, 1166656, 1166657, 1166658, 1166659,
               1166662, 1166664, 1166665, 1166667, 1166668, 1166669, 1166671, 1166672, 1166673, 1166674, 1166675,
               1166676, 1166677, 1166678, 1166679, 1166680, 1166681, 1166682, 1166683, 1166685, 1166688, 1166689,
               1166693, 1166696, 1166697, 1166698, 1166699, 1166700, 1166701, 1166702, 1166704, 1166705, 1166706,
               1166707, 1166709, 1166710, 1166712, 1166713, 1166714, 1166716, 1166717, 1166718, 1166719, 1166721,
               1166722, 1166723, 1166725, 1166726, 1166727, 1166728, 1166730, 1166731, 1166733, 1166734, 1166735,
               1166736, 1166741, 1166742, 1166743, 1166744, 1166745, 1166747, 1166748, 1166749, 1166751, 1166752,
               1166753, 1166754, 1166755, 1166756, 1166757, 1166758, 1166759, 1166760, 1167155, 1167157, 1167158,
               1167539, 1167540, 1167546, 1167966, 1167967, 1168007, 1168010, 1168011, 1168012, 1168014, 1168015,
               1168016, 1168017, 1168018, 1168019, 1168020, 1168021, 1168022, 1168023, 1168024, 1168025, 1168026,
               1168027, 1168028, 1168029, 1168030, 1168031, 1168032, 1168033, 1168034, 1168035
    )
order by t.id, t.language_id

这导致(仅示例):

不过我想要的是 id 一个 结果行,其中特定 language_idtext 作为额外附加列。

我的意思是:

Name id bg cs de ...
MobileServices 1166401` bg translated text cs translated text de translated text ...

有人知道怎么做吗?我尝试了 crosstab 函数,但由于 sql 需要是函数中的字符串,所以我在找出错误堆栈跟踪时遇到了问题。 任何帮助表示赞赏! 谢谢

您可以使用条件聚合。 Postgres 为此目的提供 filter

select tm.name, t.id,
       max(t.text) filter (where t.language_id = 'bg') as bg,
       max(t.text) filter (where t.language_id = 'cs') as cs,
       . . .
from translate_dev.tab_translation t join
     modules tm
     on tm.translation_id = t.id
        
where t.id in (. . . )
group by tm.name, t.id