从SQL中获取具有唯一记录的最小日期

时间:2014-01-17 13:04:03

标签: sql-server group-by sql-order-by unique

我有表说VendorReport在这个表中我有三列ID,PrefixId,Download_date 我表中的数据如下

ID      PrefixId Download_date

1   VIS017  28-09-2012
2   VIS028  29-09-2012
3   VIS035  29-09-2012
4   VIS028  30-09-2012
5   VIS028  29-09-2012
6   VIS028  01-10-2012
7   VIS025  30-09-2012

我想要具有最小日期的唯一PrefixId记录,如下所示

1   VIS017  28-09-2012
2   VIS028  29-09-2012
3   VIS035  29-09-2012
4   VIS025  30-09-2012

所以我尝试了这个查询但没有得到预期的结果。

select VendorReport.PrefixId,VendorReport.Download_Date from VendorReport
join (select PrefixId, MIN(Download_Date) d_date from VendorReport group by PrefixId) t2 on VendorReport.PrefixId= t2.PrefixId order by VendorReport.Download_Date asc

4 个答案:

答案 0 :(得分:1)

我是sql server的新手,请试试这个

select prefixId,min(download_date) as download_date from #abc group by prefixId order by prefixId asc

答案 1 :(得分:0)

试试这个..............

select Row_number() over ( order by x.Download_date),x.PrefixId,x.Download_date
(
select PrefixId,Min(Download_date)  Download_date
from 
VendorReport 
group by Prefixid
) x

答案 2 :(得分:0)

你去吧

create table #VendorReport(
 ID int,
 PrefixId nvarchar(50),
 Download_date datetime
)


insert into #VendorReport values(1,'IS017','2012-09-28');
insert into #VendorReport values(2,'IS028','2012-09-29');
insert into #VendorReport values(3,'IS035','2012-09-29');
insert into #VendorReport values(4,'IS028','2012-09-30');
insert into #VendorReport values(5,'IS028','2012-09-29');
insert into #VendorReport values(6,'IS028','2012-10-01');
insert into #VendorReport values(7,'IS025','2012-09-30');

 select * from #VendorReport
 select ROW_NUMBER() OVER(ORDER BY PrefixId) as Id, PrefixId, min(Download_date) as Download_date from #VendorReport group by PrefixId


drop table #VendorReport

答案 3 :(得分:0)

目前尚不清楚你想要得到什么。希望这会有所帮助:

WITH T AS
(
select 
     VendorReport.*,
     ROW_NUMBER() OVER (PARTITION BY PrefixID 
                        ORDER BY Download_date, ID) as RowNum
from VendorReport
)
SELECT ID,PrefixId, Download_date 
FROM T 
WHERE RowNum=1
Order by Download_Date DESC

SQLFiddle demo