订阅更新

各品类周一到周日的销量:日期转星期再行转列

SQL 实战 123 题 · 第 114 题 困难 约 2 分钟读完

LeetCode 1479 · 星期函数、行转列、零值

本文目录
  1. 面试怎么回答
  2. 题意
  3. 表结构
  4. 思路
  5. 参考解法
  6. 易错点

面试怎么回答

商品 LEFT JOIN 订单,用 DAYOFWEEK(order_date) 得到星期,按品类分组,SUM(CASE WHEN 星期 = 2 THEN quantity ELSE 0 END) AS Monday 这样写七列。注意 DAYOFWEEK 里周日是 1,和 WEEKDAY 的编号不同。

先把这段讲顺;面试官追问时,再展开下面的原理和细节。

详细讲解

题意

订单表记录订单日期、商品和数量,商品表记录商品所属品类。输出每个品类在周一到周日每天(按星期汇总,不分哪一周)的销售数量,没有销量的填 0,按品类排序。

表结构

  • Orders:order_id、customer_id、order_date、item_id、quantity;(order_id, item_id) 为主键
  • Items:item_id(主键)、item_name、item_category

思路

先把订单日期转成星期几,再按品类分组,用七个条件求和把星期转成七列。以商品表为主表 LEFT JOIN 订单,没有任何订单的品类也会出现,各列为 0。MySQL 的 DAYOFWEEK 把周日记为 1、周一记为 2,要对应好。

参考解法

select item_category as category, 
sum(case when num = 2 then quantity else 0 end) as Monday,
sum(case when num = 3 then quantity else 0 end) as Tuesday,
sum(case when num = 4 then quantity else 0 end) as Wednesday,
sum(case when num = 5 then quantity else 0 end) as Thursday,
sum(case when num = 6 then quantity else 0 end) as Friday,
sum(case when num = 7 then quantity else 0 end) as Saturday,
sum(case when num = 1 then quantity else 0 end) as Sunday
from
(select item_category, quantity,dayofweek(order_date) as num from 
items i left join orders o 
on i.item_id=o.item_id) t
group by item_category
order by item_category

易错点

  • DAYOFWEEK 周日是 1,WEEKDAY 周一是 0,两个函数别混用。
  • 从订单表出发会漏掉没有销量的品类。
刷题进度保存在当前浏览器