You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求Databricks SQL查询语句:计算Finished projected date字段

需求与解决方案:Databricks SQL计算完成预计日期

输入表

Load_dateprojected_datetotal demandrolling consumed demand
2020-01-012020-01-0110060
2020-01-012020-01-0215075
2020-01-012020-01-03200100
2020-01-012020-01-04300120
2020-01-012020-01-05400160

期望输出表

Load_dateprojected_datetotal demandrolling consumed demandFinished projected date
2020-01-012020-01-01100602020-01-03
2020-01-012020-01-02150752020-01-05
2020-01-012020-01-03200100---
2020-01-012020-01-04300120---
2020-01-012020-01-05400160---

计算逻辑

针对每条记录的total demand,找到第一个满足rolling consumed demand大于等于该值对应的projected_date;若不存在符合条件的日期,则显示---。

示例:

  • 当projected_date为2020-01-01时,total demand是100,rolling consumed demand在2020-01-03达到100,因此该记录的Finished projected date为2020-01-03;
  • 当projected_date为2020-01-02时,total demand是150,rolling consumed demand在2020-01-05达到160(大于150),因此对应的Finished projected date为2020-01-05。

Databricks SQL查询语句

WITH demand_data AS (
    SELECT 
        Load_date,
        projected_date,
        `total demand`,
        `rolling consumed demand`
    FROM your_table_name -- 替换为你的实际表名
)
SELECT 
    d1.Load_date,
    d1.projected_date,
    d1.`total demand`,
    d1.`rolling consumed demand`,
    COALESCE(
        MIN(d2.projected_date), 
        '---'
    ) AS `Finished projected date`
FROM demand_data d1
LEFT JOIN demand_data d2 
    ON d2.`rolling consumed demand` >= d1.`total demand`
GROUP BY d1.Load_date, d1.projected_date, d1.`total demand`, d1.`rolling consumed demand`
ORDER BY d1.projected_date;

语句说明

  1. 用CTEdemand_data封装原始数据,简化后续关联逻辑;
  2. 通过自左关联匹配所有满足rolling consumed demand≥当前记录total demand的行;
  3. 用MIN(d2.projected_date)筛选出最早符合条件的日期;
  4. 用COALESCE处理无匹配结果的场景,返回---;
  5. 按projected_date排序,保证结果顺序与期望一致。

内容的提问来源于stack exchange,提问作者Johnson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 03:01:09