日期:2014-05-18  浏览次数:20366 次

求个sql...??
A表
spid khid zdrq sl
2325 318 2012-02-15 00:00:00.000 3000
2325 318 2011-03-10 17:05:33.000 600
2325 318 2011-03-10 17:05:33.000 11400
2325 318 2012-01-16 00:00:00.000 3000
B表
id spid khid xyksrq xyjsrq
1 2325 318 2011-01-01 00:00:00.000 2011-12-31 00:00:00.000
2 2325 318 2012-01-01 00:00:00.000 2012-12-31 00:00:00.000
求结果(合计a表在b表中日期范围内的合计数量)
id spid khid hjsl
1 2325 318 12000
2 2325 318 6000

------解决方案--------------------
SQL code
select b.id,b.spid,b.khid ,sum( sl) from a,b 
where a.spid=b.spid and a.khid =b.khid 
and a.zdrq  between xyksrq and xyjsrq
group by b.id,b.spid,b.khid

------解决方案--------------------
SQL code

create table A
(
 spid int,
 khid int,
 zdrg datetime,
 s1 int
)

create table B
(
 id int,
 spid int,
 khid int,
 xyksrq datetime,
 xyjsrq datetime
)


insert into A 
select 2325, 318, '2012-02-15 00:00:00.000', 3000 union all
select 2325, 318, '2011-03-10 17:05:33.000', 600 union all
select 2325, 318, '2011-03-10 17:05:33.000', 11400 union all
select 2325, 318 ,'2012-01-16 00:00:00.000', 3000

insert into B
select 1,2325,318,'2011-01-01 00:00:00.000', '2011-12-31 00:00:00.000' union all
select 2,2325,318, '2012-01-01 00:00:00.000', '2012-12-31 00:00:00.000'


select *,hjsl=(select SUM(s1) from A where zdrg between t1.xyksrq and t1.xyjsrq) from B t1