聚合并计算mysql中的值

时间:2018-09-11 14:49:21

标签: mysql sql database mysqli

我有一个表,其中包含一些传入和传出的数据。

+====+===========+==========+============+
| id | flow(int) | quantity | product_id |
+====+===========+==========+============+
| 1  | 0         | 100      | 1          |
+----+-----------+----------+------------+
| 2  | 1         | 20       | 1          |
+----+-----------+----------+------------+
| 3  | 1         | 30       | 1          |
+----+-----------+----------+------------+
| 4  | 0         | 10       | 1          |
+----+-----------+----------+------------+
| 5  | 1         | 30       | 2          |
+----+-----------+----------+------------+
| 6  | 2         | 10       | 2          |
+----+-----------+----------+------------+
| 7  | 0         | 10       | 2          |
+====+===========+==========+============+

列流是一种枚举,0-传入,1和2-传出操作。

如何获得特定产品的当前“余额”?

产品1应该具有“余额” 60 =入库(100)-出库(20)-出库(30)+入库(10)。

产品2的“余额”应该为-30 =支出(30)-支出(10)-收入(10)。

可以通过单个查询以任何有效的方式进行查询吗?

3 个答案:

答案 0 :(得分:3)

使用以下内容:

public boolean shouldOverrideUrlLoading(WebView webView, String url) {
    if (url.endsWith(".pdf")){
        try{
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            intent.setPackage("com.android.chrome");                    
            cordova.getActivity().startActivity(intent);
            return true;
        }catch(android.content.ActivityNotFoundException e){
            LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
        }
    } else if (url.contains("/icsdownload/")){
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        cordova.getActivity().startActivity(intent);
    }
}

答案 1 :(得分:1)

这将是条件聚合:

select product_id,
       sum(case when flow like 'out_%' then - quantity else quantity end) as net_quantity
from t
group by product_id;

答案 2 :(得分:0)

With incoming_product as(
   select product_id,sum(quantity) res
   from my_table
   where flow = 0
   group by product_id
),
outgoing_product as(
   select product_id,sum(quantity) res
   from my_table
   where flow <> 0
   group by product_id
)
select t1.product_id, t1.res - t2.res
from incoming_product t1,outgoing_product t2
where t1.product_id = t2.product_id;