如何在派生列中排除具有空值的行?

时间:2016-04-21 03:33:14

标签: sql sql-server

我正在运行查询,我使用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。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:4)

您可以将查询包装在另一个选择中并在那里执行过滤:

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