SQL使用QUALIFY获取最低的两个值

问题描述 投票:1回答:1

我需要在测试日期后根据加入测试表获得最低(最早)2个日期。我已经尝试过运行QUALIFY-ROW_NUMBER-PARTITION,这在示例中看起来非常简单,但它对我的查询并不好看。 QUALIFY之前的一切都有效。我没有正确实现QUALIFY,或者我应该只使用其他方法。

SELECT p.[ENTITY_ID]
,[PROD_DATE]
,[WTR]
,[WCNT]
,[DAYS]
,t.max_TEST_DATE
,wt.TEST_DATE
,wt.TEST_VOL 
FROM (SELECT [ENTITY_ID]
,max([TEST_DATE]) as max_TEST_DATE
FROM [dbo].[PDEN_TEST]
group by ENTITY_ID) as t 
INNER JOIN [dbo].[PDEN_WELL_TEST] wt
on t.max_TEST_DATE = wt.TEST_DATE and t.ENTITY_ID = wt.ENTITY_ID
inner join [dbo].[PDEN_PROD] p
on p.ENTITY_ID = t.ENTITY_ID
where PROD_DATE >= TEST_DATE
qualify 
row_number() over (partition by p.ENTITY_ID, [PROD_DATE]) <=2

由于Gordon而修改如下,但我只是第一次出现每个Entity_ID而不是2

SELECT top (2) with ties p.[ENTITY_ID]
,[PROD_DATE]
,[WTR]
,[WCNT]
,[DAYS]
,t.max_TEST_DATE
,wt.TEST_DATE
,wt.TEST_VOL as IP24
FROM (SELECT [ENTITY_ID]
,max([TEST_DATE]) as max_TEST_DATE
FROM [DI].[dbo].[PDEN_WELL_TEST]
group by ENTITY_ID) as t 
INNER JOIN [DI].[dbo].[PDEN_WELL_TEST] wt
on t.max_TEST_DATE = wt.TEST_DATE and t.ENTITY_ID = wt.ENTITY_ID
inner join [DI].[dbo].[PDEN_PROD] p
on p.ENTITY_ID = t.ENTITY_ID
where PROD_DATE >= TEST_DATE
ORDER BY row_number() OVER (partition BY p.ENTITY_ID ORDER BY PROD_DATE)

ENTITY_ID PROD_DATE WTR WCNT DAYS max_TEST_DATE TEST_DATE IP24 60916 1998-12-01 1395 1 31 1998-11-21 1998-11-21 160 60919 1997-11-01 242 1 30 1997-10-10 1997-10-10 9776 60920 1993 -04-01 50710 1 30 1993-04-01 1993-04-01 173 60921 1994-07-01 8300 1 14 1994-06-26 1994-06-26 0 60928 2017-04-01 38733 1 30 2017-03-03 -14 2017-03-14 232 60926 2017-06-01 20379 1 20 2017-05-08 2017-05-08 29 60929 2001-07-01 8288 1 31 2001-06-09 2001-06-09 68

sql sql-server partition row-number
1个回答
1
投票

我想你只需要order by部分:

qualify row_number() over (partition by p.ENTITY_ID order by PROD_DATE) <= 2

如果在SQL Server中确实需要此功能,则可以执行以下操作:

select top (2) with ties . . .
from . . .
. . .
order by row_number() over (partition by p.ENTITY_ID order by PROD_DATE)

这在SQL Server中也是如此。

© www.soinside.com 2019 - 2024. All rights reserved.