窗口函数 - 选择最近的行

时间:2017-08-19 15:19:22

标签: sql-server sql-server-2012 window-functions

我需要根据创建日期选择最近的行。 这是我的表:

REF X      REF Y            EMLOYEE CREATION DATE
2879074 DLP/2015.01551-B.01 Didier  3/5/2015
2879074 DLP/2015.00841-A.01 Didier  2/5/2015
2879074 DLP/2015.00146-A.01 jacques 1/8/2015
2879074 DLP/2014.07840-A.02         1/6/2015
2879074 DLP/2014.05967-B.03 diet    6/21/2016
2879074 DLP/2014.05967-B.03 ext     6/21/2016
2879074 DLP/2014.05967-B.02 David   10/21/2015
2879074 DLP/2014.05967-B.02 ieva    10/21/2015
2879074 DLP/2014.05967-B.02 laetitia10/21/2015
2879074 DLP/2014.05967-B.02 PLN 10/21/2015
2879074 DLP/2014.05967-B.01 David   4/14/2015
2879074 DLP/2014.05967-B.01 ieva    4/14/2015
2879074 DLP/2014.05967-B.01 laetitia4/14/2015
2879074 DLP/2014.05967-B.01 PLN    4/14/2015
2733407 DLP/2014.00138-B.03 Andy    9/6/2016
2733407 DLP/2014.00138-B.03 Nell    9/6/2016
2733407 DLP/2014.00138-B.03 stephane9/6/2016
2733407 DLP/2014.00138-B.02 Andy    2/17/2016
2733407 DLP/2014.00138-B.02 Nell    2/17/2016
2733407 DLP/2014.00138-B.02 nicola  2/17/2016
2733407 DLP/2014.00138-B.02 diet    2/17/2016
2733407 DLP/2014.00138-B.01 herve   3/10/2015
2733407 DLP/2014.00138-B.01 nicola  3/10/2015

输出应为:

Ref x   Ref y   employee           Creation Date
2879074 DLP/2014.05967-B.03 diet    6/21/2016
2879074 DLP/2014.05967-B.03 ext     6/21/2016
2733407 DLP/2014.00138-B.03 Andy    9/6/2016
2733407 DLP/2014.00138-B.03 Nell    9/6/2016
2733407 DLP/2014.00138-B.03 stephane9/6/2016

我猜我必须使用窗口功能,但我无法列出正确的REF Y.任何帮助将不胜感激 非常感谢

1 个答案:

答案 0 :(得分:0)

如果您要查找最近的5行,您只需执行此操作:

SELECT TOP 5 * FROM [tablename] ORDER BY [Creation Date] DESC

除非您尝试实现更复杂的功能,否则不需要窗口功能。