我在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;
这是数据,
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
这是我想得到的结果:
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
任何人都知道为了得到这个结果我必须做什么查询?
答案 0 :(得分:1)
您可以使用条件聚合:
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
答案 1 :(得分:0)
Sagi的解决方案很好,使用很多类型你可以创建一个生成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