问题
Given is a Postgres table like this
nummer vorname name cash
------|-----------|-----------|-----
1 paul smith 500
2 andy london 700
2 mike dover 700
3 clara winchester 200
To query this table my sql looks like this right know:
SELECT
nummer,
vorname,
name,
cash as total
FROM
data.myTable
GROUP BY
nummer,
name,
vorname,
cash
ORDER BY
nummer;
Is it possible to concat the two rows where nummer is the same (in this case 2).
Means my output should look like this (cash will also have the same values if the numbers are equal):
nummer vorname name cash
------|-----------|-----------|-----
1 paul smith 500
2 andy london 700
mike dover
3 clara winchester 200
回答1:
Use GROUP BY and the aggregate functioin string_agg():
SELECT nummer
,string_agg(vorname, E'\n') AS vorname
,string_agg(name, E'\n') AS name
,cash
FROM mytable
GROUP BY nummer, cash
ORDER BY nummer, cash;
I added cash to the GROUP BY to get to the original value and safeguard against the case where it would be different for the same nummer.
As to your comment:
is it possible to unique the query also by names. means if 2|andy london|700 is listed twice one should be removed.
SELECT nummer
,string_agg(vorname, E'\n') AS vorname
,string_agg(name, E'\n') AS name
,cash
FROM (
SELECT DISTINCT
nummer, vorname, name, cash
FROM mytable
) AS m
GROUP BY nummer, cash
ORDER BY nummer, cash;
回答2:
SELECT nummer,
array_to_string(array_agg(vorname), E'\n'),
array_to_string(array_agg(name), E'\n'),
cash
FROM mytable
group by nummer, cash;
That should do it.
来源:https://stackoverflow.com/questions/12370083/concat-rows-in-postgres