2012-01-27 106 views
0

我有這個查詢返回正確的數據,但我想過濾它。通過唯一ID和將來最早的日期過濾SQL查詢

SELECT  TOP (100) PERCENT dbo.Reg_Master.id, dbo.Cart_Programs.cartid, dbo.Reg_Master.F_ID, dbo.BlockPeriod.profileid, dbo.Reg_Master.FirstName, 
         dbo.Reg_Master.LastName, dbo.BlockPeriod.startdate, dbo.Cart_Programs.blockid 
FROM   dbo.Cart_Programs LEFT OUTER JOIN 
         dbo.Reg_Master ON dbo.Cart_Programs.cartid = dbo.Reg_Master.cartid LEFT OUTER JOIN 
         dbo.BlockPeriod ON dbo.Cart_Programs.blockid = dbo.BlockPeriod.id 
WHERE  (dbo.BlockPeriod.profileid = xxx) AND (dbo.Reg_Master.F_ID = xxxx) 
ORDER BY dbo.BlockPeriod.startdate 

對於每個dbo.Reg_Master.id,我想只返回最早dbo.BlockPeriod.startdate(即今天或更高版本 - 換句話說,忽略了已經通過日期)每個dbo.Reg_Master.id,我似乎無法得到它正確格式化。

回答

1

首先,TOP 100 Percent什麼都不做,優化器會忽略它。 此外,您的左連接不起任何作用,因爲您的WHERE條件,所以我編輯了SQL以使用inner join + cross apply vs outer join + outer apply

如果我對每個Reg_Master記錄正確理解您,您最多隻需要從BlockPeriod獲取1條記錄,其中1條記錄是距離當天日期更近的最近日期。

如果是這樣,那麼你正在尋找的是一個APPLY表操作員TOP (1)組合,如下圖所示:

修訂

SELECT Reg_Master.id, 
     Cart_Programs.cartid, 
     Reg_Master.F_ID, 
     T.profileid, 
     Reg_Master.FirstName, 
     Reg_Master.LastName, 
     T.startdate, 
     Cart_Programs.blockid 
FROM Cart_Programs 
JOIN Reg_Master ON Cart_Programs.cartid = Reg_Master.cartid 
CROSS APPLY(
    SELECT TOP 1 * FROM BlockPeriod 
    WHERE BlockPeriod.id = Cart_Programs.blockid 
     AND BlockPeriod.profileid = xxx AND Reg_Master.F_ID = xxxx 
     AND BlockPeriod.startdate >= GETDATE() 
ORDER BY BlockPeriod.startdate ASC 
) AS T 
+0

感謝您的幫助,但在這個例子。它根本不會過濾結果,所有記錄的startdate值都爲NULL。任何其他想法? – 2012-01-27 05:02:59

+0

@resonantmedia - 我的不好,讓我編輯sql – 2012-01-27 05:04:29

+0

@resonantmedia再試一次我已經更新了帖子+ sql – 2012-01-27 05:23:42