我有一张 table :
CREATE TABLE [dbo].[t]
(
[ID] [uniqueidentifier] NOT NULL,
[RoomID] [BIGINT] NOT NULL,
[RateID] [BIGINT] NOT NULL,
[Discount] [money] NOT NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NOT NULL,
[IsActive] [bit] NOT NULL,
[CreationDate] [datetime] NOT NULL
)
和一些数据:
RoomID RateID Discount StartDate EndDate
103716801 3011657 20.00 2014-09-30 00:00:00.000 2014-10-05 00:00:00.000
103716801 3011657 0.00 2014-09-28 00:00:00.000 2014-10-26 00:00:00.000
103716801 3011657 40.00 2014-09-29 00:00:00.000 2014-10-03 00:00:00.000
我的要求:
DECLARE
@iBeginDate DATE,
@iEndDate DATE
SELECT
@iBeginDate = getdate()
,@iEndDate = Dateadd(dd, 30, getdate());
WITH Calendar AS (
SELECT @iBeginDate AS tDate
UNION ALL
SELECT dateadd(DAY , 1, tDate) AS tDate
FROM Calendar
WHERE dateadd (DAY, 1, tDate) <= @iEndDate
)
SELECT c.tDate, t.*
FROM Calendar c
OUTER APPLY (select top 1 * from t where startdate <= c.tDate and c.tDate between startdate and enddate order by StartDate DESC) t
OPTION (MAXRECURSION 0)
这是一些回复:
2014-10-25 103716801 3011657 0.00 2014-09-28 00:00:00.000 2014-10-26 00:00:00.000
2014-10-26 103716801 3011657 0.00 2014-09-28 00:00:00.000 2014-10-26 00:00:00.000
2014-10-27 NULL NULL NULL NULL NULL NULL
2014-10-28 NULL NULL NULL NULL NULL NULL
2014-10-29 NULL NULL NULL NULL NULL NULL
2014-10-30 NULL NULL NULL NULL NULL NULL
如果我可以满足 apply 中的条件,我将更改(翻转)另一个语句 - 但我不能。
我需要保存应用并添加其他内容
问题: 如何将最后一个值的行放入可为空的行中?任何想法...
例如:
select case when exists( /*outer apply*/ )
then OUTER APPLY (select top 1 * from roomratesrelation where startdate <= c.tDate and c.tDate between startdate and enddate order by StartDate desc) t
else OUTER APPLY (select top 1 * from roomratesrelation where startdate <= c.tDate and order by StartDate desc) t1
最佳答案
好吧,我讨厌这个答案,我为写它感到难过,但它可能有用。如果其他人提出更好的解决方案,我会很高兴地删除它。
SELECT c.tDate,
ISNULL(t1.RoomID, t2.RoomID) AS RoomID,
ISNULL(t1.RateID, t2.RateID) AS RateID
ISNULL(t1.Discount, t2.Discount) AS Discount
ISNULL(t1.StartDate, t2.StartDate) AS StartDate,
ISNULL(t1.EndDate, t2.EndDate) AS EndDate
FROM Calendar c
OUTER APPLY (
select top 1 *
from t
where startdate <= c.tDate
and c.tDate between startdate and enddate
order by StartDate DESC
) t1
OUTER APPLY (
SELECT t3.RoomID, t3.RateID, t3.Discount, t3.StartDate, t3.EndDate
FROM t t3
WHERE t3.ID = (
SELECT MAX(t4.ID)
FROM t t4
)
)t2
OPTION (MAXRECURSION 0)
我还没有测试过这个,所以请告诉我它是否/如何失败,我会看看是否可以更新它。
关于SQL 外部应用条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26166820/