使用postgresql返回行的连接

时间:2016-09-16 16:51:31

标签: postgresql group-by

在我的表格中我有这种情况

|  id    |       book                      | reg   |    cif                       | nm  |    end        | nr |aa | bb  |    type     | 
|12134357|"Lv.2-Registro Geral (matrícula)"|"10001"|"1002414002024400386-90705793"|     |"Ataulfo Alves"|1877|"G"|"102"|             |
|12134356|"Lv.2-Registro Geral (matrícula)"|"10001"|""                            |"RUA"|"Ataulfo Alves"|1877|"G"|"102"|"Apartamento"|
|12134358|"Lv.2-Registro Geral (matrícula)"|"10001"|""                            |""   |"Ataulfo Alves"|    |"" |""   |"Apartamento"|
 

可以使用一个选择(按书分组和reg我只返回一行包含所有信息?如果我使用DISTINCT,她会将每个相等的值分组。

结果示例:

|"Lv.2-Registro Geral (matrícula)"|"10001"|"1002414002024400386-90705793"|"RUA|"Ataulfo Alves"|1877|"G"|"102"|"Apartamento"|

TKS

2 个答案:

答案 0 :(得分:1)

DEMO

SELECT book,
       MAX("reg"), 
       MAX("cif"), 
       MAX("nm"), 
       MAX("end"), 
       MAX("nr"),
       MAX("aa"),
       MAX("bb"),
       MAX("type")
FROM  table1
GROUP BY book;

<强>输出

|                              book |                        max |                            max |   max |             max |  max | max |   max |           max |
|-----------------------------------|----------------------------|--------------------------------|-------|-----------------|------|-----|-------|---------------|
| "Lv.2-Registro Geral (matrícula)" | January, 01 10001 00:00:00 | "1002414002024400386-90705793" | "RUA" | "Ataulfo Alves" | 1877 | "G" | "102" | "Apartamento" |

答案 1 :(得分:0)

我不确定你到底想要完成什么,但是下面(非常难看)的查询会找到每个字段的第一个非空值并立即返回所有字段:

SELECT
    (SELECT "id"   FROM mytable WHERE coalesce(length("id"   || '') > 0, false) ORDER BY id LIMIT 1),
    (SELECT "book" FROM mytable WHERE coalesce(length("book" || '') > 0, false) ORDER BY id LIMIT 1),
    (SELECT "reg"  FROM mytable WHERE coalesce(length("reg"  || '') > 0, false) ORDER BY id LIMIT 1),
    (SELECT "cif"  FROM mytable WHERE coalesce(length("cif"  || '') > 0, false) ORDER BY id LIMIT 1),
    (SELECT "nm"   FROM mytable WHERE coalesce(length("nm"   || '') > 0, false) ORDER BY id LIMIT 1),
    (SELECT "end"  FROM mytable WHERE coalesce(length("end"  || '') > 0, false) ORDER BY id LIMIT 1),
    (SELECT "nr"   FROM mytable WHERE coalesce(length("nr"   || '') > 0, false) ORDER BY id LIMIT 1),
    (SELECT "aa"   FROM mytable WHERE coalesce(length("aa"   || '') > 0, false) ORDER BY id LIMIT 1),
    (SELECT "bb"   FROM mytable WHERE coalesce(length("bb"   || '') > 0, false) ORDER BY id LIMIT 1),
    (SELECT "type" FROM mytable WHERE coalesce(length("type" || '') > 0, false) ORDER BY id LIMIT 1);