MySQL从一个包含一列的表创建两列

时间:2014-12-08 03:12:12

标签: mysql select inner-join self-join

我是MySQL的新手,下面是我的第一个声明基本上是:)

我需要帮助。

我在mysql中有这个表定义:

id | item_id |价格| def =可以是AB

我需要构建一个新表,其中包含两列我将拥有的列 按价格分组的项目,分为def = A和def = B

的项目

我尝试使用自我加入,它会创建两列,但它只按def = A的价格分组,而不是A的价格和B的价格明显分组。

这是我到目前为止所处的地方:

SELECT a.`id` as A_id,  a.`item_id` as A_ITEM_id, a.`def` as A_def, a.price as A_PRICE,
b.`id` as B_id,  b.`item_id` as B_ITEM_id, b.`def` as B_def, b.price as B_PRICE

FROM table as a, table as b where 
a.`def` = 'A' AND b.`def` = 'B' GROUP by A_PRICE;

我试图按照A_PRICE分组,B_PRICE - 并没有真正起作用。

1 个答案:

答案 0 :(得分:1)

您需要case based aggregation将def行值转换为列

<强> SQL Fiddle

select item_id, price,
       max(case when def='A' then 'A' end) as A, 
       max(case when def='B' then 'B' end) as B
from table1
group by item_id, price
相关问题