简体   繁体   中英

MySQL Create two columns from a table with one column

I am really new to MySQL, below is one of my first statement basically:)

I need help.

I have this table definition in mysql:

id | item_id | price | def = could be A or B

I need to build a new table with two columns out of this one where I will have items grouped by price and separated into items with def = A and def = B

I've tried to use self join and it creates two columns, but it groups only by price of def = A, not distinctly by price of A and price of B.

This is where I've gotten so far:

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;

I've tried to group by A_PRICE,B_PRICE - doesn't really work.

you need a case based aggregation to convert def row values into columns

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM