如下所示给出一个名为OrderInfo的表格,我想总结每个订单的数量和价格。
表:
OrderID | Cost | Qty
0001 | 1.1 | 1
0001 | 2.2 | 3
0001 | 3.3 | 2
0002 | 10 | 5
0003 | 4.5 | 1
0003 | 9.9 | 1
...
结果:
OrderID | Cost | Qty
0001 | 6.6 | 6
0002 | 10 | 5
0003 | 14.4 | 2
...
尝试:
SELECT OrderID, Sum(Cost) AS TotCost, Sum(Qty) AS TotQty
FROM OrderInfo
GROUP BY OrderID
我的最终目标是使用结果表来获取每个订单的平均值,因此如果有一个更简单的方法来获得它而不需要总结成本和数量,那么该解决方案将会很好!
结束目标:
OrderID | Average
0001 | 1.1
0002 | 2.00
0003 | 7.2
答案 0 :(得分:-1)
要获得所需的值,只需将计算除以:
SELECT OrderID, Sum(Cost) AS TotCost, Sum(Qty) AS TotQty,
Sum(Cost) / Sum(Qty) AS AvgPerUnit
FROM OrderInfo
GROUP BY OrderID;