【发布时间】:2015-07-31 18:18:31
【问题描述】:
我有一个数据集,其中包含订单日期及其变体(week()、year()、weekday() 等)。当且仅当订单日期满足特定条件(例如,周 = 51,年 = 2015)时,我想创建对订单单位求和的逻辑。
我正在寻找的输出:
product_id, product_sku, 星期一_单位_售出, 星期二_单位_已售出, 星期三_单位_已售出, thursday_units_sold, friday_units_sold, 星期六_单位_售出, sunday_units_sold
这里需要注意的是,如果订单日期发生在上周,我只希望在那些日子出售单位。另外,我不希望这个计算依赖于 where 子句中的任何标准。我已经缩短了请求以使其保持简单,但实际上我将在一个 select 子句中查看不同的时间范围(迄今为止的生命、mtd、ytd 等)。
这是我目前无法使用的代码。
select
product_id,
sku_code,
case when week = current_week and year = current_year and weekday = 0 then sum(units_sold) end as monday_units,
case when week = current_week and year = current_year and weekday = 1 then sum(units_sold) end as tuesday_units,
case when week = current_week and year = current_year and weekday = 2 then sum(units_sold) end as wednesday_units,
case when week = current_week and year = current_year and weekday = 3 then sum(units_sold) end as thursday_units,
case when week = current_week and year = current_year and weekday = 4 then sum(units_sold) end as friday_units,
case when week = current_week and year = current_year and weekday = 5 then sum(units_sold) end as saturday_units,
case when week = current_week and year = current_year and weekday = 6 then sum(units_sold) end as sunday_units
from
-- This table is at the order level whereas the final result rolls up into the product/sku level.
(select
order_date,
order_id,
product_id,
sku_code,
weekday(order_date) as weekday,
week(order_date) as week,
month(order_date) as month,
year(order_date) as year,
yearmonth(order_date) as yearmonth,
units_sold,
product_sales,
-- I tried calculating this in each case when in the select statement above,
-- but moved it down here in an attempt to problem solve why my calculations aren't working.
week((curdate() - interval 1 day)) as current_week,
year((curdate() - interval 1 day)) as current_year,
from product_sales
) a
【问题讨论】:
-
你在外部查询中没有遗漏
GROUP BY sku_code, weekday之类的东西吗?
标签: mysql