我做的是考勤系统。
表关系如下:
a表:人员信息,主要字段有ID,name(姓名),cardid(卡号)
b表:cardid(卡号),times(刷卡记录)
表里的数据大致如下:
a:
1,张三,kd1
2,李四,kd2
3,王五,kd3
b:
kd1,2012/10/23 08:30……
kd1,2012/10/23 16:30……
kd2,2012/10/23 08:30……
kd2,2012/10/23 16:30……
…………
描述一下,每个人都有张卡,每个人每天都有可能不只刷一两次卡。现在我们考勤统计,比如说10月份张三的考勤记录。
1到31号都要,当天没有刷卡记录就显示缺勤。
每一列代表一天,不管你刷了多少次卡,只显示最早和最晚。
好了就这样,我写的有点多,对高手来说可能很简单,希望各位高手不惜赐教。先谢过!!
------最佳解决方案--------------------
;WITH a(ID, Name, cardid) AS
(
select 1, '张三', 'kd1' union all
select 1, '李四', 'kd2' union all
select 1, '王五', 'kd3'
),
b(cardid, refreshtime) AS --卡号,刷卡时间
(
select 'kd1', '2012/10/23 08:30' union all
select 'kd1', '2012/10/23 16:30' union all
select 'kd2', '2012/10/23 08:30' union all
select 'kd2', '2012/10/23 16:30' union all
select 'kd2', '2012/10/23 17:00'
) --准备表a和表b数据
---查询
select distinct
a.ID,
a.Name,
(select MIN(b.refreshtime) from b where b.cardid = a.cardid) '最早刷卡时间',
(select MAX(b.refreshtime) from b where b.cardid = a.cardid) '最晚刷卡时间'
from a
ID Name 最早刷卡时间 最晚刷卡时间
----------- ---- ------------------ ----------------
1 张三 2012/10/23 08:30 2012/10/23 16:30
1 李四 2012/10/23 08:30 2012/10/23 17:00
1 王五 NULL NULL
(3 row(s) affected)
------其他解决方案--------------------
use Tempdb
go
if not object_id(N'Tempdb..#1') is null
drop table #1
Go
create table #1 (cardid varchar(4),times datetime)
insert into #1
select 'kd1','2012-10-23 08:00:00' union all
select 'kd1','2012-10-23 18:00:00' union all
select 'kd2','2012-10-23 07:00:00' union all
select 'kd2','2012-10-23 19:00:00' union all
select 'kd1','2012-10-24 08:00:00' union all
select 'kd1','2012-10-24 18:00:00'
GO
if not object_id(N'Tempdb..#2') is null
drop table #2
Go
create table #2 (name varchar(8),cardid varchar(4))
insert into #2
select '张三','kd1' union all
select '李四','kd2' union all
select '王五','kd3'
GO
----------------------------
declare @s varchar(8000)
set @s=''
Select
@s=@s+','+quotename(convert(varchar(10),[Times],120))+'='
+'isnull('
+'convert(varchar(8),min(case when convert(varchar(10),[Times],120)='+quotename(convert(varchar(10),[Times],120),'''')+' then [Times] else null end),108)'