SQL查询替换Report_Date当前日期为指定日期生成账龄方案
账龄查询固定核算基准日期修改方案
需求说明
原查询默认以系统当前日期getdate()作为核算基准生成账龄,现需要支持指定任意固定日期(如2021-06-01)作为核算基准生成对应时点的账龄数据。
修改思路
- 新增专用变量存储核算基准日期,仅需修改变量赋值即可切换核算时点,无需调整其他业务逻辑
- 统一替换查询中所有用到
getdate()的基准日期逻辑,保证Report_Date输出和账龄区间计算口径完全一致
完整修改后代码
-- 仅需修改此处的日期值即可切换核算基准 DECLARE @ReportDate DATETIME = '2021-06-01' SELECT @ReportDate AS Report_Date, sum(case when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), @ReportDate) Between 0 and 30 then B.CurrentBalance else 0 end) '0-30', sum(case when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), @ReportDate) Between 31 and 60 then B.CurrentBalance else 0 end) '31-60', sum(case when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), @ReportDate) Between 61 and 90 then B.CurrentBalance else 0 end) '61-90', sum(case when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), @ReportDate) Between 91 and 120 then B.CurrentBalance else 0 end) '91-120', B.Primary_Payer_Code, B.Secondary_Payer_Code, B.CurrentResponsibility_desc, Case When G.PAYER_GROUP IS NOT NULL Then G.PAYER_GROUP Else Case When B.Primary_Payer_Code = 'PP' Then 'SELF PAY' Else F.Description End End AS Payer_Description FROM Date D with (nolock) JOIN TEL_BILLED_LINE_ITEM_ODS B with (nolock) ON ( convert(datetime,convert(char,B.Original_Bill_Date,101)) = D.DATE) LEFT OUTER JOIN TBLPAYER_ODS P with (nolock) ON B.Primary_Payer_Code=P.Code LEFT OUTER JOIN TBLFINANCIALCLASS_ODS F with (nolock) ON F.tblfinancialclassid = P.FinancialClassID LEFT OUTER JOIN PAYER_GROUP G ON G.PAYER_CODE = P.CODE WHERE ( B.CurrentBalance != 0) AND B.BadDebtFlagYN=0 AND B.Primary_Payer_Code !='CL' -- exclude CLIENT 07/01/2010 jdw GROUP BY B.Primary_Payer_Code, B.Secondary_Payer_Code, B.CurrentResponsibility_desc, Case When G.PAYER_GROUP IS NOT NULL Then G.PAYER_GROUP Else Case When B.Primary_Payer_Code = 'PP' Then 'SELF PAY' Else F.Description End End
注意事项
- 日期赋值格式建议使用
YYYY-MM-DD标准格式,避免不同数据库日期格式兼容性问题 - 若需要保持原Report_Date的字符串拼接格式输出,可将第一行输出替换为
convert(datetime,convert(char,datepart(mm,@ReportDate))+'/'+convert(char,datepart(dd,@ReportDate))+'/'+convert(char,datepart(yyyy,@ReportDate))) AS Report_Date,逻辑完全一致
内容的提问来源于stack exchange,提问作者JL Thalacker
相关产品推荐
相关产品推荐

