2014-04-14 24 views
2

我有过去的记录一个巨大的表格看起来类似于此的值从一个字段中的值:试图选择基于日期字段,其中第一个值不为空

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值,其中startDate is not NULL。所以我理想的输出是这样的:

field1, field2, field3, startDate 
-------------------------------------- 

1  A   B  1/2/2014 
2  C   D  1/17/2014 

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

回答

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 
+0

干杯@Serpiton :) –

+0

我在写同样的查询,刷新后我不要和拼写检查你的:) – Serpiton

+0

到OP:ROW_NUMBER()是一个SQLServer 2005或更好功能 – Serpiton

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

相关问题