[英]PostgreSQL select query 'join multiple rows to one row'
I am new to PostgreSQL. 我是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. 数据作为一行来自文件,并作为5行保存在数据库中。 What I want is to make a SELECT statement where it will combine the 5 rows again into one. 我想要的是创建一个SELECT语句,它将5行再次组合成一个。
eg 例如
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? 这可能吗?
You could use ( SQL Fiddle ): 你可以使用( 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.