分组排序后,如何取得组的第一条记录

select * from 表 a
where 日期=(select top 1 日期 from 表 where 编号=a.编号 order by 日期 desc)
--或:
select a.* from 表 a,(select 编号,日期=max(日期) from 表 group by 编号)b
where a.编号=b.编号 and a.日期=b.日期

--或:
select * from 表 a
where not exists(
 select * from 表 where 编号=a.编号 and 日期>a.日期)

如何在查询的时候添加一个虚拟的序号字段

摘txlicenhe (马可) :
1: 自增列   类型为:int identity(1,1)  当然也可以是bigint,smallint
   eg: create table tbName(id int identity(1,1),description varchar(20))
   或在用企业管理器设计表字段时,将字段设为int,将标识设为是,其它用默认即可

2: 查询时加序号:
  a:没有主键的情形:
   Select identity(int,1,1) as iid,* into #tmp from TableName
   Select * from #tmp
   Drop table #tmp
  b:有主键的情形:
   Select (Select sum(1) from TableName where KeyField <= a.KeyField) as iid,* from TableName a
3:生成自增序列号的表
  eg: 生成一列0-30的数
   Select top 30 (select sum(1) from sysobjects where name<= a.name)-1 as id from sysobjects a

  当然,可能sysobjects 中没有这么多条记录,比如只有100条,我需生成1-800的序列号
  如下处理:
Select (Select sum(1) from (Select top 800 a.name as name1,b.name as name2 from sysobjects a ,sysobjects b) cc where name1<= dd.name1 and name2 <= dd.name2 ) from
(Select top 800 a.name as name1,b.name as name2 from sysobjects a ,sysobjects b) dd


应用举例
eg1:
 create table t(日期 char(8),请假人数 int)
 insert t select '20031001',3
 Union all select '20031003',2
 Union all select '20031004',1
 Union all select '30031031',5
 要列出2003年10月每一天的请假人数,若没有,以0表示。

Select convert(char(8),dateadd(day,id,'20031001'),112),IsNull(t.请假人数,0) from
(Select top 31 (select sum(1) from sysobjects where name<= a.name)-1 as id from sysobjects a) bb
left join t on convert(char(8),dateadd(day,id,'20031001'),112) = t.日期

eg2: 生成随机考勤打卡资料:

declare @r int
--得到要处理的记录数
set @r=900

--创建得到随机时间的临时表
create table #tb(id int identity(1,1),dt1 datetime,dt2 datetime,dt3 datetime,dt4 datetime,dt5 datetime,dt6 datetime)

--生成随机时间
declare @sql varchar(8000)
set @sql='insert into #tb(dt1,dt2,dt3,dt4,dt5,dt6) select top '+cast(@r as varchar)+'
 dateadd(ss,rand(a.id)*1800,''07:30''),
 dateadd(ss,rand(a.id+1)*400,''11:30''),
 dateadd(ss,rand(a.id+2)*1600,''13:00''),
 dateadd(ss,rand(a.id+3)*300,''17:30''),
 dateadd(ss,rand(a.id+4)*800,''17:45''),
 dateadd(ss,rand(a.id+5)*250,''20:00'')
 from(select top 100 id from sysobjects) a,
 (select top 9 id from sysobjects) b
order by newid()
exec(@sql)
当然,如果将07:30 11:30 ...这些时间改成排班时间就更好了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值