我有一個表:SQL外與報考條件
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
如果我可以在適用條件,我會改變(翻轉)另一種說法 - 但我不能。
我需要保存申請,並添加別的東西
問題: 如何把最後一行價值在可空行?任何想法...
例如:
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
您能否重新說明您的問題。這沒有意義。 – Arun 2014-10-02 18:13:06
所以,只是爲了清楚起見,你希望它的工作,以便如果列爲空,它默認爲前一行的值,是否正確?我很難提出一個確切的解決方案,但你可能能夠做一些子查詢和ISNULL – guildsbounty 2014-10-02 18:40:55
@guildsbounty你是對的 - 但是怎麼...我打破了我的想法,但沒有什麼 – Hurricane 2014-10-02 18:43:50