繁体   English   中英

MySQL从一个表创建两列

[英]MySQL Create two columns from a table with one column

我对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分组-确实没有用。

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

SQL小提琴

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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