尝试根据日期字段的值从字段中选择值,其中第一个值不为NULL

时间:2014-04-14 20:23:26

标签: sql sql-server

我有一张过去记录的大表,看起来与此相似:

field1,    field2,   field3,   startDate, lastUpdate
--------------------------------------------------
 1         A        B       NULL       3/1/2014
 1         A        B       1/5/2014   3/2/2014
 1         A        B       1/7/2014   3/3/2014
 1         A        B       1/2/2014   3/4/2014 
 1         A        B       NULL       3/5/2014
 2         C        D       1/28/2014  3/1/2014
 2         C        D       1/17/2014  3/2/2014
 2         C        D       NULL       3/3/2014
 2         C        D       NULL       3/4/2014 
 2         C        D       NULL       3/5/2014

我正在尝试编写一个查询,我可以将field1,field2和field3转换为一个不同的记录,然后让startDate值基于最新的lastUpdate值{{1 }}。所以我理想的输出结果如下:

startDate is not NULL

我的SQL技能不是那么强大,有什么想法吗?

2 个答案:

答案 0 :(得分:1)

; WITH CTE
AS 
(
   SELECT field1, field2, field3, startDate, lastUpdate,
       ROW_NUMBER() OVER (PARTITION BY field1, field2, field3 
                          ORDER BY lastUpdate DESC) AS RN
   FROM Table_Name 
   WHERE startDate IS NOT NULL
) 
SELECT  field1, field2, field3, startDate, lastUpdate
FROM CTE 
WHERE RN = 1

答案 1 :(得分:0)

您可以进行自我加入以找到最大的lastUpdated

select field1, field2, field3, startDate
from table t1
where startDate is not null
  and not exists (select * from table t2 
                  where t1.field1=t2.field1 
                    and t1.field2=t2.field2 
                    and t1.field3=t2.field3
                    and startDate is not null
                    and t1.lastUpdate<t2.lastUpdate)

这将过滤所有具有null startDate的行,并且对于每个集合,它将忽略具有相同条件和较大lastUpdate值的行的所有行。

工作sql fiddle