日期:2014-05-17 浏览次数:20691 次
if OBJECT_ID('customer') is not null drop table customer
create table customer
(
cardno int,
Fare decimal(10,2)
)
if OBJECT_ID('consume') is not null drop table consume
create table consume
(
cardno int,
confare decimal(10,2)
)
if OBJECT_ID('cashrec') is not null drop table cashrec
create table cashrec
(
cardno int,
cashfare decimal(10,2)
)
insert into customer
select 1,20 union
select 2,40 union
select 3,70 union
select 4,70
insert into consume
select 1,20 union
select 1,40 union
select 2,70 union
select 2,70
insert into cashrec
select 1,10 union
select 1,30 union
select 2,60 union
select 2,80
select * from customer
go
with cte
as
(
select t.cardno,(case when SUM(t2.cashfare)-SUM(t1.confare) is not null then SUM(t2.cashfare)-SUM(t1.confare)
else sum(t.Fare) end) Fare
from
customer t
left join consume t1 on t.cardno=t1.cardno
left join cashrec t2 on t.cardno=t2.cardno
group by t.cardno
)
update customer set Fare=
(
select cte.Fare
from
cte
where cte.cardno=customer.cardno
)
select * from customer