MySQL: 取两列乘以代表第三列的列总和
MySQL: get sum of columns with multiply two columns on behalf of third column
我试图通过将两个列值与 where 条件相乘来获取所有行的总和,但出现 mysql 的一些错误。在尝试了一些例子后,我得到了我的结果,但我不知道那是不是正确的方法:
Table: store_stocks
我只想根据增值税、非增值税和总库存计算库存数量,数量乘以数量。
我刚刚创建了那个查询:
SELECT sum(qty*sale_price) as total_stock,
(select sum(qty*sale_price) from store_stocks where vat_status = 0 and store_id = 8) as non_vat_stock,
(select sum(qty*sale_price) from store_stocks where vat_status = 1 and store_id = 8) as with_vat_stock
FROM `store_stocks` where store_id = 8 group by store_id
及其显示结果:
谁能告诉我有没有其他方法可以实现这个,因为我认为这个查询有点复杂,每次我在子查询中使用 where 并且我还必须在 [=12 中实现这个查询=].
你不需要子查询,你可以在sum()
中使用一个条件让它只汇总特定的记录:
SELECT sum(qty*sale_price) as total_stock,
sum(if(vat_status = 0, qty*sale_price, 0)) as non_vat_stock,
sum(if(vat_status = 1, qty*sale_price, 0)) as with_vat_stock
FROM `store_stocks` where store_id = 8 group by store_id
您也可以使用 case
表达式代替 if()
函数。
我试图通过将两个列值与 where 条件相乘来获取所有行的总和,但出现 mysql 的一些错误。在尝试了一些例子后,我得到了我的结果,但我不知道那是不是正确的方法:
Table: store_stocks
我只想根据增值税、非增值税和总库存计算库存数量,数量乘以数量。
我刚刚创建了那个查询:
SELECT sum(qty*sale_price) as total_stock,
(select sum(qty*sale_price) from store_stocks where vat_status = 0 and store_id = 8) as non_vat_stock,
(select sum(qty*sale_price) from store_stocks where vat_status = 1 and store_id = 8) as with_vat_stock
FROM `store_stocks` where store_id = 8 group by store_id
及其显示结果:
谁能告诉我有没有其他方法可以实现这个,因为我认为这个查询有点复杂,每次我在子查询中使用 where 并且我还必须在 [=12 中实现这个查询=].
你不需要子查询,你可以在sum()
中使用一个条件让它只汇总特定的记录:
SELECT sum(qty*sale_price) as total_stock,
sum(if(vat_status = 0, qty*sale_price, 0)) as non_vat_stock,
sum(if(vat_status = 1, qty*sale_price, 0)) as with_vat_stock
FROM `store_stocks` where store_id = 8 group by store_id
您也可以使用 case
表达式代替 if()
函数。