zoukankan      html  css  js  c++  java
  • SQL两表更新

    Product(pid,name,amount,nowAmount):标识,名称,已有数量,当前数量
    Trade(id,pid,operType,number):标识,产品标识,操作类型(入库:1,出库:0),数量

    Product表中测试数据:

    1 苹果 100 0
    2 桔子  50 0

    Trade表中测试数据:
    1 1 1 432
    2 1 0 50
    3 2 1 20
    4 2 0 40
    5 1 1 30
    6 2 0 20

    现要求一条SQL语句更新Product表中nowMount值
    语句如下:
    update p set p.nowAmount = p.amount+t.number
    from Product as p ,(select pid,sum(case operType when '0' then number* (-1)  else number endnumber 
    from Trade group by pid) as t where t.pid=s.pid
    或者
    update p
    set p.nowAmount= t.number+p.amount
    from Product as p 
    inner join (select pid ,sum(case operType when '0' then number* (-1)  else number endas number from Trade group by pid) as t
    on p.pid=t.pid
    两者一样执行后Product表:
    1 苹果 100 512
    2 桔子 50 10
  • 相关阅读:
    Linux Apache服务(一)
    mysql基础
    linux面试题一
    linux shell(2)
    linux基础汇总2
    python列表生成式、生成器,迭代器与二分法
    python的函数
    python函数
    java 翁老师学习笔记-持续更
    责任链模式
  • 原文地址:https://www.cnblogs.com/ywkpl/p/1101276.html
Copyright © 2011-2022 走看看