Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL select query 'join multiple rows to one row'

Tags:

sql

postgresql

I am new to PostgreSQL. My case is that I have a table where I store my data. The data come from a file as one row and are getting saved in the database as 5 rows. What I want is to make a SELECT statement where it will combine the 5 rows again into one.

e.g.

id  id2  id3  year  code   value
4   1    1    1642  radio  30
4   1    1    1642  tv     56
4   1    1    1642  cable  67
4   1    1    1642  dine   70

I want to have a query where it will return the following:

id  id2  id3  year  radio  tv  cable dine
4   1    1    1642  30     56  67   70

The values of the code are becoming columns with values the actual values.

Is this possible?

like image 805
maria_k Avatar asked Sep 29 '22 21:09

maria_k


1 Answers

You could use (SQL Fiddle):

SELECT m.id, m.id2, m.id3, m.year,
  SUM(CASE WHEN m.code = 'radio' THEN m.value END) as radio,
  SUM(CASE WHEN m.code = 'tv' THEN m.value END) as tv,
  SUM(CASE WHEN m.code = 'cable' THEN m.value END) as cable,
  SUM(CASE WHEN m.code = 'dine' THEN m.value END) as dine
FROM MyTable m
GROUP BY m.id, m.id2, m.id3, m.year
like image 74
Linger Avatar answered Oct 03 '22 00:10

Linger