【问题标题】:How can I transpose table values in postgresql?如何在 postgresql 中转置表值?
【发布时间】:2021-07-23 03:30:30
【问题描述】:

如何转置这些值以获取此表:

让它看起来像这样:

没有可以在 postgresql 中使用的 Pivot 函数,每次尝试交叉表函数时,我的代码中都会出现错误。假设我的表名为 select * from TAttributes

【问题讨论】:

标签: sql postgresql pivot crosstab


【解决方案1】:

使用条件聚合,在 Postgres 中表示filter

select id,
       max(attributenumber) filter (where attributeid = 2000),
       max(attributenumber) filter (where attributeid = 2001),
       max(attributenumber) filter (where attributeid = 2002),
       max(attributenumber) filter (where attributeid = 2003)
from t
group by id;

Here 是一个 dbfiddle。

【讨论】:

  • 不幸的是,这只会给我整个空值
  • @oaker 。 . .我添加了一个 dbfiddle。该代码有效并回答了您的问题。
  • 看起来成功了!我可以对日期做同样的事情吗?例如,max(attributedate)过滤器(其中attributeid = 2007)等。我正在尝试,但它给了我一个错误:sytanx error at or near "max"
  • 是的,您可以使用日期。 MAX() 几乎适用于所有数据类型。
【解决方案2】:

试试这个:

SELECT id,  
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2000)) AS '2000',
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2001)) AS '2001',
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2002)) AS '2002',
    MAX((SELECT attributenumber FROM public.t WHERE ext_t.id = id AND ext_t.attribuiteid = attribuiteid AND attribuiteid = 2003)) AS '2003' 
FROM public.t ext_t GROUP BY id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2023-02-11
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多