34,575
社区成员
发帖
与我相关
我的任务
分享
select 卡号,工号,
[上班时间]=max(case when [读卡机名称]='上班' then 刷卡日期+' '+刷卡时间 end),
[下班时间]=max(case when [读卡机名称]='下班' then 刷卡日期+' '+刷卡时间 end)
from Tb
group by 卡号,工号
卡号 工号 上班时间 下班时间
----------- ----------- --------------------- ---------------------
20001 60001 2009-8-5 09:25:23 2009-8-5 17:25:23
20002 60002 2009-8-5 08:39:00 2009-8-5 17:55:43
(所影响的行数为 2 行)
select 卡号,工号,刷卡日期,
上班时间=min(convert(nvarchar(10),刷卡日期,120)+' '+刷卡时间),
下班时间=max(convert(nvarchar(10),刷卡日期,120)+' '+刷卡时间)
from tb
group by 卡号,工号,刷卡日期
[Quote=引用 1 楼 htl258 的回复:]
同一天同一工号只有一次上下班还是有多次?
[/Quote]
正是,如果就一次,好说,
select 卡号 ,工号,刷卡日期,
MAX(case when 读卡机名称 ='上班' then CONVERT(VARCHAR(10),刷卡时间,120)+CONVERT(VARCHAR(5),刷卡时间,108) end) 上班时间,
max(case when 读卡机名称 ='下班' then CONVERT(VARCHAR(10),刷卡时间,120)+CONVERT(VARCHAR(5),刷卡时间,108)) 下班时间
from tb
group by 卡号 ,工号,刷卡日期
select
卡号,
工号,
max(case when 读卡机名称='上班 ' then convert(varchar(10),刷卡日期,120)+' '+刷卡时间 end) as 上班时间,
max(case when 读卡机名称='下班 ' then convert(varchar(10),刷卡日期,120)+' '+刷卡时间 end) as 下班时间
from
tb
group by
卡号,工号
selct A.卡号,A.工号,A.刷卡日期 上班时间,B.刷卡日期 下班时间
from tb A
inner join tb B
on A.卡号=B.卡号
and convert(char(8),A.刷卡日期,120)=convert(char(8),B.刷卡日期,120)
and A.刷卡日期<B.刷卡日期
---------------------------------
-- Author: htl258(Tony)
-- Date : 2009-08-05 09:49:57
---------------------------------
--> 生成测试数据表:tb
If not object_id('[tb]') is null
Drop table [tb]
Go
Create table [tb]([卡号] int,[工号] int,[刷卡日期] varchar(10),[刷卡时间] varchar(10),[读卡机名称] nvarchar(2))
Insert tb
Select 20001,60001,'2009-8-5','08:25:23','上班' union all
Select 20001,60001,'2009-8-5','17:25:23','下班'
Go
--Select * from tb
-->SQL查询如下:
select 卡号,工号,
上班时间=max(case [读卡机名称] when '上班' then [刷卡日期]+' '+[刷卡时间] end),
下班时间=max(case [读卡机名称] when '下班' then [刷卡日期]+' '+[刷卡时间] end)
from tb
group by 卡号,工号
/*
卡号 工号 上班时间 下班时间
----------- ----------- --------------------- ---------------------
20001 60001 2009-8-5 08:25:23 2009-8-5 17:25:23
(1 行受影响)
*/
如果一次.select 卡号,
工号,
max(case when 读卡机名称='上班 ' then convert(nvarchar(10),刷卡日期,120)+' '+刷卡时间 end) as 上班时间,
max(case when 读卡机名称='下班 ' then convert(nvarchar(10),刷卡日期,120)+' '+刷卡时间 end) as 下班时间
from tb
group by 卡号,工号
select 卡号 ,工号,刷卡日期,
min(case when 读卡机名称 ='上班' then 刷卡时间 else '23:59:59' end) 上班时间,
max(case when 读卡机名称 ='下班' then 刷卡时间 else '00:00:00' end) 下班时间
from tb
group by 卡号 ,工号,刷卡日期