当前位置: 代码迷 >> Sql Server >> 一句搞定统计整个表的SQL语句怎么写
  详细解决方案

一句搞定统计整个表的SQL语句怎么写

热度:12   发布时间:2016-04-24 09:53:20.0
一句搞定统计整个表的SQL语句如何写?
二个表,
表1:vatistock
[goodsid] [nvarchar](20),
[quantity] [decimal](9,5)
表2:vatibill
[stockid] [nvarchar](20),
[quantity] [decimal](9,5),
[buyorsale] [tinyint]--1代表买,2代表卖

vatibill中的stockid全部来自vatistock的goodsid
现在要统计vatibill所有商品的库存数量.也就是把表1:vatistock的quantity根据表2的实际进销情况来更新
用一句sql语句写如何写
update vatistock set quantity=.....
------解决思路----------------------
引用:
update vatistock set quantity=sum(case when a.[buyorsale]=2 then a.[quantity]*(-1) else a.[quantity] end) from vatibill as a where [stockid]=a.[goodsid]

小调一下

update vatistock set quantity=(select sum(case when a.[buyorsale]=2 then a.[quantity]*(-1) else a.[quantity] end) as qty from vatibill as a where [goodsid]=vatistock.[stockid]) 
  相关解决方案