2016-02-05 90 views
2

我希望每個不同號碼的日期最早的行。我創建了這個腳本,但問題是我繼續獲取最新的記錄。在表格中選擇舊記錄

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 

任何幫助,將不勝感激。謝謝

回答

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

您應該使用的,而不是MAX函數MIN函數

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])) 
0

這樣簡單

SELECT PSEUDO, NUMBER , MIN ([LAST CONTACT DATE]) FROM [DATA].[DBO].[IAPT] T1 
    GROUP BY PSEUDO, NUMBER