我希望每个不同号码的日期最早的行。我创建了这个脚本,但问题是我一直在获取最新的记录。
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
任何帮助将不胜感激。谢谢
答案 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_NUMBER
与PARTITION 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]))