我有一个包含以下三列的表格:
value
date
id
对于每个ID,我想使用订购日期确定第一个值。这是有效的方法吗?:
;with cte as
(
select
id
,date
,value
,ROW_NUMBER() OVER (PARTITION BY id ORDER BY date asc) AS RN
from Bla
where value is not null
)
select
*
from cte
where RN = 1
答案 0 :(得分:1)
是的,这是一种有效的方法。我会以相同的方式进行操作,也许一开始就没有星号,也没有分号(因为我也不用句号来开始一个句子):
WITH
cte (id, [date], [value], RN) AS (
SELECT id, [date], [value],
ROW_NUMBER() OVER (PARTITION BY id ORDER BY [date])
FROM Bla
WHERE [value] IS NOT NULL
)
SELECT id, [date], [value]
FROM cte
WHERE RN = 1;
答案 1 :(得分:1)
另一种方法是使用TOP 1 WITH TIES
,对记录进行如下排序:
SELECT TOP 1 WITH TIES id, [date], [value]
FROM BLA
ORDER BY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY
CASE WHEN [value] IS NULL THEN '2525-12-31' ELSE [date] END)