SQL outer适用于条件

时间:2014-10-02 18:06:47

标签: sql tsql

我有一张桌子:

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 个答案:

答案 0 :(得分: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)

我还没有对此进行测试,所以请告诉我它是否/如何失败,我会看看是否可以更新它。