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

如何编写SQL计算租赁状态变更的间隔天数?

问题:生成租赁历史报表的SQL实现瓶颈

我不确定如何编写代码获取所需结果,希望社区能指引方向。需要针对Rent History表生成一份报表,预期样式如Final Result所示(详见附图)。

Rent History表中有三个标签,我已使用ROW_NUMBER() OVER (PARTITION BY)根据position确定租赁启用/停用的起始日期,但在此处遇到瓶颈,不知后续操作。以下是我目前编写的代码:

SELECT tag
,progress_complete_date_time
,create_date
,required_until_date
,modify_date
,on_rent_status
,[date_on-off_rent]
,position
,CASE 
    WHEN position = 1
        THEN [date_on-off_rent]
    END AS [first_time_on-off_rent]
,RANK() OVER(PARTITION BY tag  ORDER BY modify_date) AS [RANK]
FROM CleanUpB

DateOnRent和DateOffRent列取决于标签的初始状态,部分标签以DateOnRent起始,部分以DateOffRent起始。我只需捕获on_rent_status的起始和结束状态。以下是我计算DaysOnRent和DaysOffRent的公式示例:

TAG-000479 DaysOnRent
DATEDIFF(DAY,'8/12/2021','4/4/2024') = 966
DATEDIFF(DAY,'04/04/2024','06/10/2024') = 67

TAG-000479 DaysOffRent
DATEDIFF(DAY,'04/04/2024','04/04/2024') = 0
DATEDIFF(DAY,'06/10/2024',GETDATE()) = 38

TAG-001832 DaysOnRent
DATEDIFF(DAY,'03/28/2024',GETDATE()) = 112

TAG-003420 DaysOnRent
DATEDIFF(DAY,'06/24/2024',GETDATE()) = 24

内容的提问来源于stack exchange,提问作者ATL-JP

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:55:04