表
ID Type Name a1,a2,a3,CreateDate
1 1 n . . . 2014-07-20
2 1 n . . . 2014-07-19
3 2 n . . . 2014-07-22
4 3 n . . . 2014-07-22
5 4 n . . . 2014-07-20
6 4 n . . . 2014-07-19
7 5 n . . . 2014-07-20
8 1 n . . . 2014-07-18
只取5条,不重复的Type 按 CreateDate Desc 如何实现?
结果
Type CreateDate
1 2014-07-20
2 2014-07-22
3 2014-07-22
4 2014-07-20
5 2014-07-20
------解决方案--------------------
----------------------------------------------------------------
-- Author :DBA_HuangZJ(發糞塗牆)
-- Date :2014-07-23 10:43:17
-- Version:
-- Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([ID] int,[Type] int,[Name] varchar(1),[CreateDate] date)
insert [huang]
select 1,1,'n','2014-07-20' union all
select 2,1,'n','2014-07-19' union all
select 3,2,'n','2014-07-22' union all
select 4,3,'n','2014-07-22' union all
select 5,4,'n','2014-07-20' union all
select 6,4,'n','2014-07-19' union all
select 7,5,'n','2014-07-20' union all
select 8,1,'n','2014-07-18' union all
select 8,6,'n','2014-07-15'
--------------开始查询--------------------------
SELECT TOP 5 [type],createdate
FROM huang a
WHERE EXISTS (SELECT 1 FROM [huang] b WHERE a.[type]=b.[type] GROUP BY [type])
ORDER BY CreateDate DESC
----------------结果----------------------------
/*
type createdate
----------- ----------
2 2014-07-22
3 2014-07-22
4 2014-07-20
1 2014-07-20
5 2014-07-20
*/
------解决方案--------------------
select type,max(CreateDate)
from tb
group by type