簡體   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