SQL Select - transform rows in columns

跟風遠走 提交于 2019-12-13 02:37:49

问题


Quite basic, but I am stuck at the moment.

On an Informix database (no pivot option), I am searching for a dynamic way to transform the following table using SQL:

book       | info  | value
-----------------------------
Moby Dick  | price | high
Moby Dick  | stock | few
Hamlet     | price | low
Hamlet     | stock | many
Faust      | price | medium
Faust      | stock | normal

Resulting table:

book       | price  | stock
-----------------------------
Moby Dick  | high   | few
Hamlet     | low    | many
Faust      | medium | normal

Thanks for your help!


回答1:


You can aggregate based on CASE expression grouped by book. Try something like this.

SELECT book,
MAX(CASE WHEN info = 'price' THEN value END) as price,
MAX(CASE WHEN info = 'stock' THEN value END) as stock
FROM table1
GROUP BY book


来源:https://stackoverflow.com/questions/38246875/sql-select-transform-rows-in-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!