我是MySQL的新手,下面是我的第一个声明基本上是:)
我需要帮助。
A
或B
我需要构建一个新表,其中包含两列我将拥有的列 按价格分组的项目,分为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 - 并没有真正起作用。
答案 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