客户表(customer)
卡号(cardno) 卡内金额(Fare)消费明细表(consume)
卡号(cardno) 消费金额(confare)充值明细表(cashrec)
卡号(cardno) 充值金额(cashfare)需要更新客户表中卡内金额
卡内金额=充值金额汇总-消费金额汇总
帮忙看这个SQL语句怎么写

解决方案 »

  1.   

    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 customergowith 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