【问题标题】:Scatter multiple rows having duplicate columns to single unique row in postgresql将具有重复列的多行分散到postgresql中的单个唯一行
【发布时间】:2019-12-18 15:29:32
【问题描述】:

如何在 sql/postgresql 中将多个重复行分散到一行中。

例如--->

让我得到 3 行

col1  col2   col3
-------------------
11    test   rat
11    test   cat
11    test   test

我想要这样的东西

col1   col2   col3  col4
------------------------
11     test   rat   cat

它与 lodash 中的 groupby 相同。但是如何在 postgresql 查询中达到同样的效果呢?

【问题讨论】:

标签: sql postgresql pivot crosstab


【解决方案1】:

您正在寻找crosstab

postgres=# create table ab (col1 text, col2 text, col3 text);
CREATE TABLE
postgres=# insert into ab values ('t1','test','cat'),('t1','test','rat'),('t1','test','test');
INSERT 0 3
postgres=# select * from crosstab('select col1,col2,col3 from ab') as (col1 text, col2 text, col3 text, col4 text);
 col1 | col2 | col3 | col4 
------+------+------+------
 t1   | cat  | rat  | test
(1 row)

披露:我为EnterpriseDB (EDB)工作

【讨论】:

  • 谢谢你,你是救世主。我不知道交叉表功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-02
  • 2020-11-30
相关资源
最近更新 更多