选择表中的旧记录

时间:2016-02-05 15:17:26

标签: sql-server sql-server-2008-r2

我希望每个不同号码的日期最早的行。我创建了这个脚本,但问题是我一直在获取最新的记录。

SELECT*
FROM
     [Data].[dbo].[IAPT] t1
WHERE
      [Last Contact Date] IN 
                              (SELECT MAX([Last Contact Date]) 
                               FROM [Data].[dbo].[IAPT] 
                                WHERE t1.[Number] =  [Data].[dbo].[IAPT].[Number] 
                          AND 
      [Last Contact Date] NOT IN
                              (SELECT MAX([Last Contact Date]) 
                               FROM [Data].[dbo].[IAPT] 
                               WHERE t1.[Pseudo] =  [Data].[dbo].[IAPT].[Pseudo]))

表:

Pseudo  Number    Last Contact Date
0X1     18        17/06/2013
0X1     18        16/04/2013
0X2     19        25/04/2013
0X2     19        16/07/2013

期望的结果:

Number      Last Contact Date
1           16/04/2013
2           25/04/2013

任何帮助将不胜感激。谢谢

3 个答案:

答案 0 :(得分:2)

您应该使用MIN功能代替MAX功能

<div class="entry-content">
    <div style="width:60%;float: left;">... more code here ...</div>
    <div style="width:33%;float: left;">... more code here ...</div>
</div>

答案 1 :(得分:1)

您可以将ROW_NUMBERPARTITION BY子句一起使用:

SELECT Pseudo, Number, [Last Contact Date]
FROM (
  SELECT Pseudo, Number, [Last Contact Date],
         ROW_NUMBER() OVER (PARTITION BY Number 
                            ORDER BY [Last Contact Date]) AS rn
  FROM [Data].[dbo].[IAPT]) AS t
WHERE t.rn = 1

每个Number分区中的第一条记录是具有最早日期的记录。

答案 2 :(得分:0)

这样简单

SELECT*
FROM
     [Data].[dbo].[IAPT] t1
WHERE
      [Last Contact Date] IN 
                              (SELECT MIN([Last Contact Date]) 
                               FROM [Data].[dbo].[IAPT] 
                                WHERE t1.[Number] =  [Data].[dbo].[IAPT].[Number] 
                          AND 
      [Last Contact Date] NOT IN
                              (SELECT MIN([Last Contact Date]) 
                               FROM [Data].[dbo].[IAPT] 
                               WHERE t1.[Pseudo] =  [Data].[dbo].[IAPT].[Pseudo]))