ID 餐别 时间
1 中餐 2009-10-25
2 中餐 2009-10-26
3 晚餐 2009-10-26
4 早餐 2009-10-27结果
1 中餐 2009-10-25
3 晚餐 2009-10-26
4 早餐 2009-10-27日期中有重复的。。我想一直得到最新的。。帮忙谢谢了
1 中餐 2009-10-25
2 中餐 2009-10-26
3 晚餐 2009-10-26
4 早餐 2009-10-27结果
1 中餐 2009-10-25
3 晚餐 2009-10-26
4 早餐 2009-10-27日期中有重复的。。我想一直得到最新的。。帮忙谢谢了
select * from tb a where not exists(select 1 from tb where a.餐别=餐别 and a.时间<时间)
--> 测试数据: @T1
declare @T1 table (ID int,餐别 varchar(4),时间 datetime)
insert into @T1
select 1,'中餐','2009-10-25' union all
select 2,'中餐','2009-10-26' union all
select 3,'晚餐','2009-10-26' union all
select 4,'早餐','2009-10-27'select * from @t1 a where not exists(select 1 from @t1 where a.餐别=餐别 and a.时间> 时间)ID 餐别 时间
----------- ---- ------------------------------------------------------
1 中餐 2009-10-25 00:00:00.000
3 晚餐 2009-10-26 00:00:00.000
4 早餐 2009-10-27 00:00:00.000(所影响的行数为 3 行)3楼有点错误
declare @T1 table (ID int,餐别 varchar(4),时间 datetime)
insert into @T1
select 1,'中餐','2009-10-25' union all
select 2,'中餐','2009-10-26' union all
select 3,'晚餐','2009-10-26' union all
select 4,'早餐','2009-10-27'select 餐别, max(时间) from @T1 group by 餐别如果不介意id的话
a.*
from
tb a
join (select max(时间)时间,餐别 from tb group by 餐别) b on
a.餐别=b.餐别
and
a.时间=b.时间
order by
时间
-- Author :fredrickhu(小F,向高手学习)
-- Date :2009-10-11 11:12:05
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([ID] int,[餐别] varchar(4),[时间] datetime)
insert [tb]
select 1,'中餐','2009-10-25' union all
select 2,'中餐','2009-10-26' union all
select 3,'晚餐','2009-10-26' union all
select 4,'早餐','2009-10-27'
--------------开始查询--------------------------
select
a.*
from
tb a
join (select max(时间)时间,餐别 from tb group by 餐别) b on
a.餐别=b.餐别
and
a.时间=b.时间
order by
时间
----------------结果----------------------------
/* ID 餐别 时间
----------- ---- -----------------------
2 中餐 2009-10-26 00:00:00.000
3 晚餐 2009-10-26 00:00:00.000
4 早餐 2009-10-27 00:00:00.000(3 行受影响)
*/