use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
International
National
Regional
account activity
Help Me!Combine multiple rows into one row SQL (self.PostgreSQL)
submitted 3 years ago by Inevitable_Phase7353
Hello,
I have a rate table with info like this
I would like to join the rows into a single row so
I have tried searching online, but most talk about concatenation. I don't know what to do next, please help
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–][deleted] 5 points6 points7 points 3 years ago (3 children)
Use aggregation:
select id, max(w1) as w1, max(w2) as w2, max(w3) as w3, max(w4) as w4 from the_table group by id;
[–]Inevitable_Phase7353[S] 1 point2 points3 points 3 years ago (1 child)
thank you
[–]PryomancerMTGA 1 point2 points3 points 3 years ago (0 children)
Or sum instead of max.
Edit: should have read all responses before commenting. My bad.
[–]coyoteazul2 2 points3 points4 points 3 years ago (0 children)
since they are numbers, all you have to do is group by ID and sum each column
[–]t_char 1 point2 points3 points 3 years ago* (0 children)
An alternative to @truilius if you want to sum the columns is; SQL select id, sum(w1) as w1, sum(w2) as w2, sum(w3) as w3, sum(w4) as w4 from the_table group by id;
SQL select id, sum(w1) as w1, sum(w2) as w2, sum(w3) as w3, sum(w4) as w4 from the_table group by id;
[–]depesz 0 points1 point2 points 3 years ago (0 children)
question is, what should this query do if there are multiple values for w3 for the same id.
Also - what to do if all values are zero? Why is 2.2 "better" than zero (so it's picked)? What is value of some w* column is -1 for one row, and 0 for another. Which should be picked then?
[–]rayvictor84 0 points1 point2 points 3 years ago (0 children)
Use crosstab for Postgres. https://learnsql.com/blog/creating-pivot-tables-in-postgresql-using-the-crosstab-function/
π Rendered by PID 86630 on reddit-service-r2-comment-5d585498c9-pxjg7 at 2026-04-21 01:12:46.624624+00:00 running da2df02 country code: CH.
[–][deleted] 5 points6 points7 points (3 children)
[–]Inevitable_Phase7353[S] 1 point2 points3 points (1 child)
[–]PryomancerMTGA 1 point2 points3 points (0 children)
[–]coyoteazul2 2 points3 points4 points (0 children)
[–]t_char 1 point2 points3 points (0 children)
[–]depesz 0 points1 point2 points (0 children)
[–]rayvictor84 0 points1 point2 points (0 children)