1

I have a table like this in my postgres BD:

CREATE TABLE foo(id,type,date,value) AS
SELECT *
FROM ( VALUES
  (11::smallint,'A','2016-06-06 19:00:00'::timestamp,81),
  (11,'A','2016-06-06 20:00:00',70),
  (11,'A','2016-06-06 21:00:00',35),
  (11,'B','2016-06-06 19:00:00',2),
  (11,'B','2016-06-06 20:00:00',0),
  (11,'B','2016-06-06 21:00:00',0)
) as f;  

Here is the data,

 id | type |        date         | value
----+------+---------------------+------
 11 | A    | 2016-06-06 19:00:00 |    81
 11 | A    | 2016-06-06 20:00:00 |    70
 11 | A    | 2016-06-06 21:00:00 |    35
 11 | B    | 2016-06-06 19:00:00 |     2
 11 | B    | 2016-06-06 20:00:00 |     0
 11 | B    | 2016-06-06 21:00:00 |     0

And this is the result that i want to get:

 ID           DATE            A   B
-----|----------------------|----|---
 11  | 2016-06-06 19:00:000 | 81 | 2
 11  | 2016-06-06 20:00:000 | 70 | 0
 11  | 2016-06-06 21:00:000 | 35 | 0

Any one knows what is the query that i have to make to get this result?

2 Answers 2

2

You can use conditional aggregation :

SELECT t.id,t.date,
       MAX(CASE WHEN t.type = 'A' THEN t.value END) as a_col,
       MAX(CASE WHEN t.type = 'B' THEN t.value END) as b_col
FROM YourTable t
GROUP BY t.id,t.date
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @sagi , it works!!! but the problem is that I have a lot of types and its very difficult for me to make the query with all of them.
Then you should use Pivot , but to tell you the truth , if its not that many, (20 or so) I prefer to use this version .
they are like 800 types...its better to use pivot in my case?
0

Sagi's solution is good , to use a lot of types You can create a request that generates the request of sagi :

 select $$SELECT t.id,t.date,$$
       ||string_agg(distinct $$MAX(CASE WHEN t.type = '$$||"type"||$$' THEN t.value END) as $$||"type"||$$_col$$,',')
       ||$$ FROM YourTable t GROUP BY t.id,t.date$$ 
   from YourTable

5 Comments

Hi @Rémy Baron I use your code combined with sagis code and the data output gives me a result with a lot of SELECT queries:
no just use my code , that generates one query based on sagi's query. Execute this generated query and you have your result
Im trying it but the console result is a text column with tuis result inside:
"SELECT t.id,t.date,MAX(CASE WHEN t.type= '486' THEN t.value END) as 486_col,MAX(CASE WHEN t.type= '487' THEN t.value END) as 487_col,MAX(CASE WHEN t.type= '488' THEN t.value END) as 488_col,MAX(CASE WHEN t.type= '489' (...)"
yes , it's your generated query now you can get this result and execute it as an new sql query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.