日期:2014-05-17 浏览次数:20613 次
;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 [Tim