I have a table like this in Firebird:

+-----------+----+------+
|vehiclename|oil |volume|
+-----------+----+------+
|v1         |oil1|12    |
+-----------+----+------+
|v2         |oil2|26    |
+-----------+----+------+
|v3         |oil1|45    |
+-----------+----+------+
|v1         |oil2|78    |
+-----------+----+------+
|v2         |oil3|95    |
+-----------+----+------+

and I want that table as

+-----------+----+----+----+
|vehiclename|oil1|oil2|oil3|
+-----------+----+----+----+
|v1         |12  |78  |0   |
+-----------+----+----+----+
|v2         |0   |26  |95  |
+-----------+----+----+----+
|v3         |45  |0   |0   |
+-----------+----+----+----+

I've tried using exists clause in case statement but no result. Any ideas?

有帮助吗?

解决方案

select vehiclename, 
       sum(case when oil = 'oil1' then volume end) as oil_1,
       sum(case when oil = 'oil2' then volume end) as oil_2,
       sum(case when oil = 'oil3' then volume end) as oil_3
from the_table
group by vehiclename
order by vehiclename;

If new oil types are added, you need to add one CASE statement for each value that can show up in the oil column.

If you need an automatic way of doing that, you will need to use dynamic SQL where you first retrieve the distinct values for the oil column and then create a SQL statement following the pattern in the above solution. Then run that dynamic SQL statement.

其他提示

SELECT vehiclename,
sum(CASE WHEN oil = 'oil1' THEN volume END) AS oil1,
sum(CASE WHEN oil = 'oil2' THEN volume END) AS oil2,
sum(CASE WHEN oil = 'oil3' THEN volume END) AS oil3
FROM test
GROUP BY vehiclename;

SQL Fiddle [MySQL version]

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top