我应该使用哪个SQL子句?

时间:2014-01-21 08:16:34

标签: sql pivot firebird

我在Firebird中有这样的表:

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

我希望该表格为

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

我尝试在case语句中使用exists子句但没有结果。 有什么想法吗?

2 个答案:

答案 0 :(得分:2)

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;

如果添加了新的油类型,则需要为CASE列中显示的每个值添加一个oil语句。

如果您需要自动执行此操作,则需要使用动态SQL,首先检索oil列的不同值,然后按照上述解决方案中的模式创建SQL语句。然后运行该动态SQL语句。

答案 1 :(得分:0)

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]