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

最佳答案

您可以将查询包装在另一个选择中,然后在其中执行过滤:

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

10-05 21:27