表:orderproducts
orderid quantity weight
-----------------------------------
4 5 0.1
4 2 0.5
5 3 2.5
5 7 0.9
1)使用以下SQL命令,可以正确计算总权重,但产品数量是忽略的。如何扩展SQL命令以查询产品数量?
select orderid, sum (weight) as totalweight from orderproducts group by orderid
现在我有了ORDERID 4的值(总重量)=> 0.6
必须正确=> 1.5
2)另外,我希望SQL命令“WHERE”(其中other_table.status =“finish”)从另一个表扩展。它也行不通。 : - (
select orderid, sum (weight) as totalweight from orderproducts where other_table.status = "finish" group by orderid
答案 0 :(得分:2)
查询:
SELECT orderid,
SUM(weight*quantity) AS totalweight
FROM orderproducts AS a
JOIN othertable AS b ON (b.orderid=b=id)
WHERE b.status = "finish"
GROUP BY orderid
答案 1 :(得分:0)
你可以试试这个:
1)产品数量:
select orderid,sum (amount) as totalamount, sum (weight) as totalweight
from orderproducts group by orderid
2)除非在其中放置子查询,否则不能将其他表放入当前查询中表的where子句中。试试这个:
select orderid, sum (weight) as totalweight from orderproducts where orderid in
(select orderid from other_table where other_table .status = "finish")
group by orderid
答案 2 :(得分:0)
1)
select orderid,sum (amount) as totalamount, sum (weight) as totalweight from orderproducts group by orderid
2) 你必须使用加入
select orderid, sum (weight*quantity) as totalweight from orderproducts as a join othertable AS b on (b.orderid=b=id) where b.status = "finish" group by orderid