maybe someone can help me out with a postgres query.
the table structure looks like this
nummer nachname vorname cash
+-------+----------+----------+------+
2 Bert Brecht 0,758
2 Harry Belafonte 1,568
3 Elvis Presley 0,357
4 Mark Twain 1,555
4 Ella Fitz 0,333
…
How can I coalesce the fields where “nummer” are the same and sum the cash values?
My output should look like this:
2 Bert, Brecht 2,326
Harry, Belafonte
3 Elvis, Presley 0,357
4 Mark, Twain 1,888
Ella, Fitz
I think the part to coalesce should work something like this:
array_to_string(array_agg(nachname|| ', ' ||coalesce(vorname, '')), '<br />') as name,
Thanks for any help,
tony
See this SQLFiddle; note that it doesn’t display the newline characters between names, but they’re still there.
The
CASEstatement is used instead ofcoalesceso you don’t have a trailing comma on entries with a last name but no first name. If you want a trailing comma, useformat('%s, %s',vorname,nachname)instead and avoid all that ugly string concatenation business:If
string_aggdoesn’t work, get a newer PostgreSQL, or mention the version in your questions so it’s clear you’re using an obsolete version. The query is trivially rewritten to usearray_to_stringandarray_agganyway.If you’re asking how to
sumnumbers that’re actually represented as text strings like1,2345in the database: don’t do that. Fix your schema. Format numbers on input and output instead, store them asnumeric,float8,integer, … whatever the appropriate numeric type for the job is.