2016-04-21 30 views
1

我正在運行一個查詢,我正在使用LEAD函數計算下一個值。問題是我需要刪除這個「下一個值」列中包含NULL的行。我無法執行WHERE NextProductID IS NULL,因爲該列是使用LEAD功能計算的。如何在派生列中排除空值的行?

示例代碼:

SELECT BusinessEntityID, ProductID, LEAD(ProductID) OVER(PARTITION BY BusinessEntityID ORDER BY BusinessEntityID) AS NextProductID 
FROM Purchasing.ProductVendor 
ORDER BY BusinessEntityID, ProductID 

我使用AdventureWorks2014。任何幫助,將不勝感激!

回答

2

你可以用你的查詢在另一個選擇有執行過濾:

SELECT data.BusinessEntityID, data.ProductID, data.NextProductID 
FROM (
    -- Your original SELECT becomes the "table" 
    SELECT BusinessEntityID, ProductID, 
     LEAD(ProductID) OVER(PARTITION BY BusinessEntityID ORDER BY BusinessEntityID) AS NextProductID 
    FROM Purchasing.ProductVendor 
    ORDER BY BusinessEntityID, ProductID 
) data 
WHERE data.NextProductID IS NOT NULL -- perform the filtering you need 
+0

工程。謝謝! –