数据来源A表:
代码 组合 日期
A001 X 2006-4-12
A001 Y 2006-4-10
A005 X 2006-4-14
A005 Y 2006-4-13
A001 X 2006-4-14
A001 Y 2006-4-14
A002 X 2006-4-15
A005 Y 2006-4-14
根据A表,求:在2006-04-10到2006-04-16各个代码在组合Y出现的记录和次数.生成的B表结果如下.
代码 在组合X首次出现日期 在组合Y出现日期 次数
A001 2006-4-12 2006-4-10 1
A005 2006-4-14 2006-4-13 1
A005 2006-4-14 2006-4-14 1
提示:在"组合Y里出现的日期"要小于或等于在"组合X首次出现的日期",如果凡大于的记录不要列出来.
不要用存储过程和创建函数.
代码 组合 日期
A001 X 2006-4-12
A001 Y 2006-4-10
A005 X 2006-4-14
A005 Y 2006-4-13
A001 X 2006-4-14
A001 Y 2006-4-14
A002 X 2006-4-15
A005 Y 2006-4-14
根据A表,求:在2006-04-10到2006-04-16各个代码在组合Y出现的记录和次数.生成的B表结果如下.
代码 在组合X首次出现日期 在组合Y出现日期 次数
A001 2006-4-12 2006-4-10 1
A005 2006-4-14 2006-4-13 1
A005 2006-4-14 2006-4-14 1
提示:在"组合Y里出现的日期"要小于或等于在"组合X首次出现的日期",如果凡大于的记录不要列出来.
不要用存储过程和创建函数.
B.代码,
B.日期 As [在组合X首次出现日期],
C.日期 As [在组合Y首次出现日期]
From (Select 代码,Min(日期) As 日期 From A Group By 代码 Where 组合='X') B
Inner Join A C
On B.代码=C.代码 And B.日期>=C.日期
Where C.组合='Y'
declare @t table(code varchar(6) ,combine varchar(2) , date1 datetime )
insert into @t
select 'A001', 'X', '2006-4-12' union
select 'A001', 'Y', '2006-4-10' union
select 'A005', 'X', '2006-4-14' union
select 'A005', 'Y', '2006-4-13' union
select 'A001', 'X', '2006-4-14' union
select 'A001', 'Y', '2006-4-14' union
select 'A002', 'X', '2006-4-15' union
select 'A005', 'Y', '2006-4-14'
select e.code,
e.x,
f.date1 as y,
count(*) as cnt from (
select code ,
(select min(date1) from @t b where a.code = b.code and b.combine = 'X') as x
from @t a
group by code
) e , @t f
where f.code = e.code
and f.combine = 'Y'
and f.date1 <= e.x group by
e.code,
e.x,
f.date1
code x y cnt
------ ------------------------------------------------------ ------------------------------------------------------ -----------
A001 2006-04-12 00:00:00.000 2006-04-10 00:00:00.000 1
A005 2006-04-14 00:00:00.000 2006-04-13 00:00:00.000 1
A005 2006-04-14 00:00:00.000 2006-04-14 00:00:00.000 1(所影响的行数为 3 行)