簡體   English   中英

在 MySQL 中旋轉表

[英]Pivoting a table in MySQL

我在最近的一次采訪中得到了這個問題。 我的 SQL 生銹了,我什至不知道從哪里開始。

這是提供的表格

-----------------------------------
date      product     quantity_sold
-----------------------------------
12/3/2019    A           200
-----------------------------------
11/6/2019    B           200
-----------------------------------
12/7/2019    B           200
-----------------------------------
10/1/2019    C           200
-----------------------------------
12/9/2019    D           200
-----------------------------------

如果只有 3 個產品 A、B 和 C 按以下格式顯示數據

date product_A_quantity_sold  product_A_quantity_sold  product_A_quantity_sold

您需要條件聚合:

select date,
  max(case when product = 'A' then quantity_sold end) product_A_quantity_sold,
  max(case when product = 'B' then quantity_sold end) product_B_quantity_sold,
  max(case when product = 'C' then quantity_sold end) product_C_quantity_sold
from tablename
group by date

如果您想在某個日期未售出產品時看到0而不是NULL ,則在每個CASE表達式中添加一個ELSE部分,例如:

max(case when product = 'A' then quantity_sold else 0 end) product_A_quantity_sold

對於 MySql,您也可以使用以下代碼:

select date,
  max((product = 'A') * quantity_sold) product_A_quantity_sold,
  max((product = 'B') * quantity_sold) product_B_quantity_sold,
  max((product = 'C') * quantity_sold) product_C_quantity_sold
from tablename
group by date

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM