SQL/MySQL:按日期将数量值拆分为多行

SQL/MySQL: split a quantity value into multiple rows by date

我有一个包含三列的 table:planning_start_date - planning_end_date - quantity

例如我有这个数据:

 planning_start_date | planning_end_date | quantity
          2019-03-01 |        2019-03-31 |     1500

我需要将值 1500 分成多行,每天平均,所以 1500 / 31 天 = 48,38 每天。

预期结果应该是:

date         daily_qty
2019-03-01 |     48,38
2019-03-02 |     48,38
2019-03-03 |     48,38
...
2019-03-31 |     48,38

有人有什么建议吗?

如果您决定升级到 MySQL 8.0,这里有一个递归 CTE,它将生成 planning_start_dateplanning_end_date 之间所有日期的列表以及所需的每日数量:

WITH RECURSIVE cte AS (
    SELECT planning_start_date AS date, 
           planning_end_date, 
           quantity / (DATEDIFF(planning_end_date, planning_start_date) + 1) AS daily_qty
    FROM test
    UNION ALL
    SELECT date + INTERVAL 1 DAY, planning_end_date, daily_qty
    FROM cte
    WHERE date < planning_end_date
)
SELECT `date`, daily_qty
FROM cte
ORDER BY `date`

Demo on dbfiddle

在 MySLQ 8+ 中,您可以像这样使用递归 CTE:

with recursive cte(dte, planning_end_date, quantity, days) as (
      select planning_start_date as dte, planning_end_date, quantity, datediff(planning_end_date, planning_start_date) + 1 as days
      from t
      union all
      select dte + interval 1 day as dte, planning_end_date, quantity, days
      from cte
      where dte < planning_end_date
     )
select dte, quantity / days
from cte;

Here 是一个 db<>fiddle.

在早期版本中,您需要某种数字 table。例如,如果您的 table 有足够的行,您可以直接使用它:

select (planning_start_date + interval n.n day),
       quantity / (datediff(planning_end_date, planning_start_date) + 1)
from t join
     (select (@rn := @rn + 1) as n
      from t cross join
           (select @rn := 0) params
     ) n
     on planning_start_date + interval n.n day <= planning_end_date;

您可以使用任何足够 n 的 table。