mysql group sum_MySQL sum()在不同的分组依据上

bd96500e110b49cbb3cd949968f18be7.png

Ok, I have a query over two tables. I need to get two sums. I do a group by so the sum() works correctly.

SELECT sum(a.x), sum(b.y) FROM a,b GROUP BY a.n where a.n=b.m

So far this works well, but the problem is i need to group them differently for the second sum (sum(b.y)), than for the first sum (sum(a.x)).

The real query is somewhat more complex but this is my main problem.

This is what i actually try to select sum(stock.amount) - if( sold.amount IS NULL , 0, sum( sold.amount ) )

How can I solve that in one query?

解决方案

since you are not writing down the tables I am gonna make a wild guess and assume the tables are like :

stock : id, item_id, amount

sold : id, item_id, amount

then again I assume that you need the stock_in_total, sold_total, left_total counts

SELECT

stock_sums.item_id,

stock_sums.st_sum as stock_in_total,

COALESCE(sold_sums.so_sum,0) as sold_total,

(stock_sums.st_sum - COALESCE(sold_sums.so_sum,0)) as left_total

FROM (

SELECT stock.item_id as item_id, SUM(stock.amount) as st_sum

FROM stock

GROUP BY item_id

) as stock_sums

LEFT JOIN (

SELECT sold.item_id as item_id, SUM(sold.amount) as so_sum

FROM sold

GROUP by item_id

) as sold_sums ON stock_sums.item_id = sold_sums.item_id

I hope this would help.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值