在MySQL中旋转表格

时间:2019-11-01 17:17:39

标签: mysql sql

我在最近的一次采访中提出了这个问题。我的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
-----------------------------------

如果只有三个产品A,B和C以以下格式显示数据

date product_A_quantity_sold  product_A_quantity_sold  product_A_quantity_sold

1 个答案:

答案 0 :(得分:1)

您需要条件聚合:

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