简体   繁体   English

将一个sql列基于两个列求和,将另一个表与条件求和

[英]sum one sql column based on two columns another table with criteria

Table teststock : teststock

type date   time product qty
in  26-Apr  6.5 vs29    10
out 26-Apr  5.4 vs29    2
in  26-Apr  8.9 vs29    5
out 25-Apr  7.2 vs29    10
in  27-Apr  5.2 vs29    5

Table product list : product list

id  product inward  outward stock
1   vs29    20      12      8

I need sql statements for asp.net. 我需要asp.net的sql语句。

  1. sum the inward in product list from qty based on type in 根据类型将来自数量的产品列表中的内向求和
  2. sum the outward in product list from qty based on type out 根据类型汇总从数量中得出的产品列表中的外部总和
  3. finally subtract inward-outward 最终向内减去

I don't know exactly what you want, but I think you want to do something like this : 我不知道您到底想要什么,但我认为您想做这样的事情:

select a.product , sum(a.inward) inward ,sum(a.outward) outward , sum(a.inward) - sum(a.outward) stock   from (
select product , case when type = 'in' then qty else 0 end inward , 
case when type = 'out' then qty else 0 end outward
from test_stock) a
group by a.product

This is sqlfiddle link about sql query : http://sqlfiddle.com/#!6/65f06e/5 这是关于sql查询的sqlfiddle链接: http ://sqlfiddle.com/#!6/65f06e/5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM