@O.Jones 对领带值的评论很到位。
这些很容易导致意外结果,尤其是返回一年的多个结果行。
避免这种情况的一种方法是非常清楚应该返回什么记录,即您可能希望按利润排序时每年的第一个条目。下一个条目可能具有相同的利润值,但不应返回。
在 SQL 中,这可能如下所示:
WITH _profits_in_years
(YEAR, profit) as
(SELECT 1999 AS YEAR, 200 AS Profit FROM dummy UNION ALL
SELECT 1999 AS YEAR, 50 AS Profit FROM dummy UNION ALL
SELECT 2000 AS YEAR, 100 AS Profit FROM dummy UNION ALL
SELECT 2001 AS YEAR, 100 AS Profit FROM dummy UNION ALL
SELECT 2002 AS YEAR, 200 AS Profit FROM dummy UNION ALL
SELECT 2002 AS YEAR, 200 AS Profit FROM dummy UNION ALL
SELECT 2003 AS YEAR, NULL AS Profit FROM dummy
)
SELECT DISTINCT
YEAR,
FIRST_VALUE(Profit) OVER
(PARTITION BY YEAR
ORDER BY PROFIT DESC NULLS LAST)
FROM
_profits_in_years