27,580
社区成员
发帖
与我相关
我的任务
分享use test
go
if object_id('test.dbo.tb') is not null drop table tb
-- 创建数据表
create table tb
(
姓名 char(8),
ID int,
刷卡时间 datetime,
类型 varchar(20)
)
go
--插入测试数据
insert into tb select '王恒',174,'2010-09-01 19:12:32.000','下班1'
union all select '王恒',174,'2010-09-02 07:50:41.000','上班1'
union all select '王恒',174,'2010-09-02 18:27:04.000','下班1'
union all select '王恒',174,'2010-09-03 07:44:10.000','上班1'
union all select '王恒',174,'2010-09-04 08:44:04.000','迟到'
union all select '王恒',174,'2010-09-04 11:31:15.000','上班重复刷卡'
union all select '王恒',174,'2010-09-03 18:51:13.000','下班1'
go
--代码实现
select 姓名,ID,刷卡日期=convert(varchar(10),刷卡时间,120)
,工作天数=(case when min(类型)!='迟到' and count(类型)=2 then 1 else 0 end)
,迟到=(case when min(类型)='迟到' then 1 else 0 end)
,忘刷次数=(case when (min(类型)='迟到' and count(类型)=2) or count(类型)=1 then 1 else 0 end)
from tb
where 类型 in ('上班1','下班1','迟到')
group by 姓名,ID,convert(varchar(10),刷卡时间,120)
/*测试结果
姓名 ID 刷卡日期 工作天数 迟到 忘刷次数
--------------------------------------------------
王恒 174 2010-09-01 0 0 1
王恒 174 2010-09-02 1 0 0
王恒 174 2010-09-03 1 0 0
王恒 174 2010-09-04 0 1 1
(4 行受影响)
*/