9

我有这张桌子:

id    |   payment_id   | quantity  |  unit cost
1           633             1            750  
2           633             1            750 
3           632             2            750 
4           632             2            750 

我需要的是:

payemnt_id  |   total
    633           1500
    632           3000 

您也可以将其视为国家,然后您试图找到每个国家的总数。我确信有一些这样的教程,但 STFW 找不到。

4

4 回答 4

38

您可以简单地将公式(表达式)放入SUM

SELECT payment_id, SUM(`unit cost` * quantity) AS total
FROM myTable
GROUP BY payment_id
于 2013-07-23T09:39:57.823 回答
3
SELECT 
    payment_id, 
    SUM(subtotal) AS total
 FROM(
    SELECT
        payment_id,
        (unit_cost * quantity) AS subtotal
) AS t1
GROUP BY 
payment_id
于 2013-07-23T09:39:43.427 回答
2
SELECT payemnt_id, SUM(`unit cost` * quantity) as total
FROM Table1
GROUP BY payemnt_id
于 2013-07-23T09:37:21.237 回答
0
SELECT COALESCE (SUM(cost_field * quantity_field),0) AS tot FROM Table_Name    

我觉得这个不错,为什么呢?因为如果他们没有结果,它会给你零

于 2020-10-26T09:15:14.650 回答