从子总数和金额计算总数

时间:2011-09-22 04:46:54

标签: sql aggregate-functions

我有一张包含购买订单数据的表格 每行包含购买的特定商品的金额,每件商品的成本和订单号组。购买的每个不同商品都是具有相同订单号的新行。

我基本上想要退回该订单的总费用。我尝试了以下但是无处可去:

SELECT order_number, SUM( sub_total ) AS `total`
FROM
  SELECT order_number, SUM( SUM( amount ) * SUM( cost_per_item ) ) AS `sub_total`
    FROM `ecom_orders`
   WHERE member_id = '4'
GROUP BY order_number
ORDER BY purchase_date DESC 

1 个答案:

答案 0 :(得分:1)

几乎所有符合SQL-92标准的RDBMS都会采用以下方法:

SELECT
order_number
,SUM(amount * cost_per_item) AS total
,purchase_date
FROM
ecom_orders
WHERE member_id = '4'
GROUP BY order_number,purchase_date
ORDER BY purchase_date DESC