我想用日期序列显示关于月份记录的关税 如果月份没有关税,则显示以前的关税 请参阅快照以获得更多说明
ALTER PROCEDURE [dbo].[Proc_MonthlyReactiveCharge_Report] @Dateset date
AS SET DATEFIRST 1 开始 DECLARE @Day int 宣布@fromDt日期 DECLARE @endDate日期 DECLARE @finalEndDate日期 DECLARE @currentdate date = GETDATE() SET @fromDt = CAST(CONVERT(varchar,DATEPART(YEAR,@ Dateset))+' - '+ CONVERT(varchar,DATEPART(MONTH,@ Dateset))+' - 01'AS date)
SET @endDate = DATEADD(s, -1, DATEADD(mm, DATEDIFF(m, 0, @fromDt) + 1, 0))
IF @endDate >= @currentdate
BEGIN
SET @finalEndDate = DATEADD(D, -DATEDIFF(D, @currentdate, @endDate) - 1, @endDate);
SET @Day = FORMAT(@finalEndDate, 'dd')
END
ELSE
SET @finalEndDate = @endDate
SET @Day = FORMAT(@finalEndDate, 'dd')
SET NOCOUNT ON;
PRINT @fromDt;
PRINT @finalEndDate;
IF 1 = 0
BEGIN
SET FMTONLY OFF
END
IF 1 = 0
BEGIN
SET FMTONLY OFF
END
CREATE TABLE #TestTable2 (
tempdate date
);
BEGIN
DECLARE @VarDate datetime = CONVERT(date, @FromDt)
WHILE @VarDate <= CONVERT(varchar, @finalEndDate)
BEGIN
INSERT INTO #TestTable2 (tempdate)
VALUES (@VarDate)
SET @VarDate = DATEADD(DAY, 1, @VarDate)
END
BEGIN
WITH tarifReactivelow
AS (SELECT
b.tariffrate AS TRL,
b.EFFECTIVEFROMDATE AS TRLeffectivefrmdate,
b.effectivetodate AS TRLeffectivetodate,
a.tempdate
FROM (SELECT
*
FROM #TestTable2) a
RIGHT JOIN T_EMS_REVENUE_TARIFFDETAILS b
ON b.TARIFFTYPE = 10
AND b.REACTIVECHARGETYPE = 2
AND (
(a.tempdate BETWEEN CONVERT(date, EFFECTIVEFROMDATE) AND CONVERT(date, EFFECTIVETODATE))
OR (a.tempdate BETWEEN CONVERT(date, EFFECTIVEFROMDATE) AND CONVERT(date, EFFECTIVETODATE)
OR CONVERT(date, EFFECTIVEFROMDATE) <= a.tempdate)
))
SELECT
*
FROM tarifReactivelow
END
DROP TABLE #TestTable2
END
END
答案 0 :(得分:1)
您可以使用tempdate
和outer apply()
top 1
的最新行
类似的东西:
select *
from #testtable2 as tt
outer apply (
select top 1 td.*
from t_ems_revenue_tariffdetails as td
where td.tarifftype=10
and td.reactivechargetype=2
and td.effectivefromdate<=tt.tempdate
order by td.effectivefromdate desc
) x
Bad habits to kick : using table aliases like (a, b, c) or (t1, t2, t3) - Aaron Bertrand