我有一个包含Child_ID,Test_ID和Test_Date
的表 Child_ID Test_ID Test_Date
1 1 2018-05-21
1 2 2018-05-22
我想找到TestNumber,所以我正在使用Rank on fly
Select Child_ID, Test_ID ,Test_Date,RANK() OVER (PARTITION BY t.Child_id order by Test_Date asc,boe.Test_ID asc) AS [TEST_NUMB]
from [Test] T
where t.Child_ID in (1)
给我结果
Child_ID Test_ID Test_Date TEST_NUMB
1 1 2018-05-21 1
1 2 2018-05-22 2
但问题是当我只选择一个测试ID时,Test_number每次都会给出'1'
select * from Test where test_ID =1
Child_ID Test_ID Test_Date TEST_NUMB
2560249 1 2018-05-21 1
select * from Test where test_ID =2
Child_ID Test_ID Test_Date TEST_NUMB
2560249 1 2018-05-21 1
我是否可以根据Test_Date获取查询以获取确切的test_number,而不插入临时表(我有数百万条记录)
答案 0 :(得分:2)
将当前查询放入CTE,然后查询:
WITH cte AS (
SELECT Child_ID, Test_ID ,Test_Date,
RANK() OVER (PARTITION BY Child_id ORDER BY Test_Date, Test_ID) AS [TEST_NUMB]
FROM [Test]
WHERE Child_ID IN (1)
)
SELECT * FROM cte WHERE test_ID = 1;
这应该有效,因为当你用精确的test_ID
查询时,等级值已经实现了(对不起,我只是想使用那个词)。
答案 1 :(得分:0)
同样是蒂姆的CTE
select *
from ( Select Child_ID, Test_ID , Test_Date
, RANK() OVER (PARTITION BY t.Child_id
order by Test_Date asc, Test_ID asc) AS [TEST_NUMB]
from [Test] T
where Child_ID = 1
) tt
where Test_ID = 1