表A:姓名,起始日期,截止日期表b: 日期,姓名,金额要计算起始日期到截止日期之间的金额我是这样写的:
select a.姓名,a.起始日期,a.截止日期,sum(金额)
from TA a inner join TB b on a.姓名=b.姓名
where b.日期>=a.日期 and b.日期<=a.截止日期
group by a.姓名,a.起始日期,a.截止日期
结果算出来数字大得吓人啊。是那里出错了啊?
select a.姓名,a.起始日期,a.截止日期,sum(金额)
from TA a inner join TB b on a.姓名=b.姓名
where b.日期>=a.日期 and b.日期<=a.截止日期
group by a.姓名,a.起始日期,a.截止日期
结果算出来数字大得吓人啊。是那里出错了啊?
--try:
select a.姓名,a.起始日期,a.截止日期,
金额=(select sum(金额) from tb where 姓名=a.姓名 and 日期 between a.起始日期 and a.截止日期)
from TA a
贴点数据看看
from TA a inner join TB b on a.姓名=b.姓名
where b.日期>=a.起始日期 and b.日期 <=a.截止日期
group by a.姓名,a.起始日期,a.截止日期
from ta a ,tb b
where b.日期 between a.起始日期 and a.截止日期
group by a.姓名,a.起始日期,a.截止日期
表A的姓名是不是有重复?
select 姓名,起始日期,截止日期,sum(金额)
from(
select distinct a.姓名,a.起始日期,a.截止日期
from TA a inner join TB b
on a.姓名=b.姓名 and b.日期>=a.日期 and b.日期 <=a.截止日期
) t
如果重复存在:
例如:XX ,2008-04-01 2008-10-10
xx, 2008-06-01,2008-09-10
这样的话,就重复计算了金额。这个问题很搞的,怎么办啊。
那你想要什么结果?……
我上面的写错了。。
select 姓名,起始日期,截止日期,sum(金额)
from(
select distinct a.姓名,a.起始日期,a.截止日期,b.金额
from TA a inner join TB b
on a.姓名=b.姓名 and b.日期>=a.日期 and b.日期 <=a.截止日期
) t
group by 姓名,起始日期,截止日期
select a.姓名,a.起始日期,a.截止日期,
金额=(select sum(金额) from tb where 姓名=a.姓名 and 日期 between a.起始日期 and a.截止日期)
from TA a
数据:
表A:
A hang, 2008-01-02,2008-03-25
A zhen, 2008-02-24,2008-05-03
A wen, 2008-05-30,2008-10-20
A hang, 2008-04-01,2008-08-20
A zhen, 2008-06-01,2008-08-30
A wen, 2008-10-22,2008-10-25
A ZHEN, 2008-09-20,2008-10-25表B(组日支出表):组别,日期,金额
A,2008-01-02 300,
A,2008-01-03 400,
A,2008-01-04 300,
A,2008-01-05 300,
A,2008-01-06 300
..... 后面的数据一样也没问题,求:人员任期内本组支出金额
即:A hang 2008-01-02,2008-03-25 金额
A zhe, 2008-02-24,2008-05-03 金额如果用:
select a.组别,a.人员,a.起始日期,a.截止日期,sum(金额)
from TA a inner join TB b on a.组别=b.组别
where b.日期>=a.起始日期 and b.日期 <=a.截止日期
group by a.人员,a.起始日期,a.截止日期 数据好像不对啊。