2014-10-02 47 views
2

我有一個表: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 
+1

您能否重新說明您的問題。這沒有意義。 – Arun 2014-10-02 18:13:06

+1

所以,只是爲了清楚起見,你希望它的工作,以便如果列爲空,它默認爲前一行的值,是否正確?我很難提出一個確切的解決方案,但你可能能夠做一些子查詢和ISNULL – guildsbounty 2014-10-02 18:40:55

+1

@guildsbounty你是對的 - 但是怎麼...我打破了我的想法,但沒有什麼 – Hurricane 2014-10-02 18:43:50

回答

2

好吧,我恨這個答案,我覺得不好寫它,但它可能工作。如果其他人提出更好的解決方案,我會很高興地刪除它。

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) 

我還沒有測試過,所以請讓我知道如果/它如何失敗,我會看看我是否可以更新它。

+1

似乎工作- 謝謝。但如何更多的表現)))) – Hurricane 2014-10-03 09:19:15

+1

可能會在最後一個使用CROSS APPLY – Hurricane 2014-10-03 10:59:17

+0

是的,這就是爲什麼我說我討厭我的答案。它確實有垃圾表現。 – guildsbounty 2014-10-03 12:35:46