第一张表:table_1 设备责任人表
id deviceId user date_begin date_end
0 001 张三 2008-01-01 2008-06-01
1 001 李四 2008-07-01 <NULL> -------------为空表示表示当前还在使用
2 002 王五 2008-01-01 <NULL> -------------为空表示表示当前还在使用
【这张表的含义是】:
设备001:1月-6月 张三在使用;
6月- 当前时间 李四在使用
设备002:1月-当前时间 王五在使用;
第二张表:table_2 使用情况表
id deviceId date_use
0 001 2008-02-01
1 001 2008-03-01
2 001 2008-04-01
3 001 2008-08-01
4 001 2008-09-01
5 002 2008-01-01
6 002 2008-09-011
【这张表的含义是】:
设备001在08年1月-6月 使用了3次(分别是2、3、4月份)--张三在使用
设备001在08年6月-当前时间 使用了3次(分别是8、9月份)--李四在使用
设备002在08年1月-当前时间 使用了2次(分别是1、9月份)--王五在使用
【我所要的结果】
id user use_times
0 张三 3次
1 李四 2次
2 王五 2次
结果的意思是:
第一张表中的每个用户一共使用了多少次(第二张表中的一条记录代表使用了一次),
【要求】一条sql语句就可以得到结果
请各位达人再帮帮忙,小弟刚接触
再次麻烦大家了
--------------------------------------------------【答案】-------------------------------------------------------
--> 测试数据: #table1
if object_id('tempdb.dbo.#table1') is not null drop table #table1
go
create table #table1 (id int,deviceId varchar(3),[user] varchar(4),date_begin datetime,date_end datetime)
insert into #table1
select 0,'001','张三','2008-01-01','2008-06-01' union all
select 1,'001','李四','2008-07-01',null union all
select 2,'002','王五','2008-01-01',null
--> 测试数据: #table2
if object_id('tempdb.dbo.#table2') is not null drop table #table2
go
create table #table2 (id int,deviceId varchar(3),date_use datetime)
insert into #table2
select 0,'001','2008-02-01' union all
select 1,'001','2008-03-01' union all
select 2,'001','2008-04-01' union all
select 3,'001','2008-08-01' union all
select 4,'001','2008-09-01' union all
select 5,'002','2008-01-01' union all
select 6,'002','2008-9-01'
select distinct id,deviceId,[user],(select count(*) from #table2 where deviceId=a.deviceId and date_use between a.date_begin and isnull(a.date_end,getdate())) as cnt
from #table1 as a
/*
---------
0 001 张三 3
1 001 李四 2
2 002 王五 2
*/