日期:2014-05-18  浏览次数:20465 次

询问一个分类提取数据的sql
数据如下
编号   产品名称   企业编号   时间
1   aaa   1   2007-5-20   18:01:00
2   bbb   1   2007-5-20   18:02:00
3   ccc   2   2007-5-20   18:03:00
4   aaa   2   2007-5-20   18:04:00
5   aaa   3   2007-5-20   18:05:00
6   bbb   3   2007-5-20   18:02:00
.......
希望取按时间排列最近的16条数据,同时一个企业只显示一个产品
5   aaa   3   2007-5-20   18:05:00
4   aaa   2   2007-5-20   18:04:00
2   bbb   1   2007-5-20   18:02:00

------解决方案--------------------
/*create table t(编号 int,产品名称 varchar(10),企业编号 int,时间 datetime)
insert t select 1, 'aaa ',1, '2007-5-20 18:01:00 '
union all select 2, 'nnn ',1, '2007-5-20 18:02:00 '
union all select 3, 'ccc ',2, '2007-5-20 18:03:00 '
union all select 4, 'zzz ',2, '2007-5-20 18:04:00 '
union all select 5, 'jjj ',3, '2007-5-20 18:05:00 '
union all select 6, 'mmm ',4, '2007-5-20 18:02:00 '
union all select 7, 'bbb ',4, '2007-5-20 18:03:00 '
union all select 8, 'bbb ',4, '2007-5-20 18:06:00 '
union all select 9, 'bbb ',4, '2007-5-20 18:03:00 '
union all select 10, 'fff ',4, '2007-5-20 18:06:00 '
union all select 11, 'bbb ',4, '2007-5-20 18:05:00 '*/

create table t(编号 int,产品名称 varchar(10),企业编号 int,时间 datetime)
insert t select 1, 'aaa ',1, '2007-5-20 18:01:00 '
union all select 2, 'bbb ',1, '2007-5-20 18:02:00 '
union all select 3, 'ccc ',2, '2007-5-20 18:03:00 '
union all select 4, 'aaa ',2, '2007-5-20 18:04:00 '
union all select 5, 'aaa ',3, '2007-5-20 18:05:00 '
union all select 6, 'bbb ',3, '2007-5-20 18:02:00 '


select 编号,产品名称,企业编号,时间 from t c where 编号 in
(
select top 2 编号 from
(
select 编号,产品名称,企业编号,时间 from t a where 产品名称 in
(
select top 1 产品名称 from
(
select top 100 percent 产品名称,企业编号 from t group by 产品名称,企业编号 order by 企业编号
)b where a.企业编号=b.企业编号
)
)d where d.企业编号=c.企业编号 order by 时间 desc
)
order by 编号 desc

drop table t

编号 产品名称 企业编号 时间
----------- ---------- ----------- ------
5 aaa 3 2007-05-20 18:05:00.000
4 aaa 2 2007-05-20 18:04:00.000
1 aaa 1 2007-05-20 18:01:00.000



------解决方案--------------------
declare @t table(编号 int, 产品名称 varchar(20), 企业编号 int, 时间 datetime)
insert @t
select 1, 'aaa ', 1, '2007-5-20 18:01:00 ' union all
select 2, 'bbb ', 1, '2007-5-20 18:02:00 ' union all
select 3, 'ccc ', 2, '2007-5-20 18:03:00 ' union all
select 4, 'aaa ', 2, '2007-5-20 18:04:00 ' union all
select 5, 'aaa ', 3, '2007-5-20 18:05:00 ' union all
select 6, 'bbb ', 3, '2007-5-20 18:02:00 '

----企业编号相同的行去时间最大的行
select top 16 * from @t as a
where not exists(select 1 from @t where 企业编号=a.企业编号 and 时间> a.时间)
order by 企业编号 desc

/*结果
5 aaa 3 2007-5-20 18:05:00
4 aaa 2 2007-5-20 18:04:00
2 bbb 1 2007-5-20 18:02:00
*/
------解决方案--------------------