我有一个SQL表如下:
+---+--------+------------+
|ID | AMOUNT | PRODUCT_ID |
+---+---------------------+
|1 | 100 | 5 |
|2 | 100 | 5 |
|3 | 100 | 5 |
|4 | 100 | 10 |
|5 | 100 | 10 |
|6 | 100 | 10 |
|7 | 100 | 10 |
+---+--------+------------+
我正在使用codeigniter并希望动态地根据SUM OF AMOUNTS
获取PRODUCT_ID
。所需的输出是:
sum of product_id 5 = 300
sum of product_id 10 = 400
答案 0 :(得分:0)
将GROUP BY
与SUM
一起使用,如下所示:
SELECT product_id, SUM(amount) AS TotalAmount
FROM tablename
GROUP BY product_id;
<强> Results 强>:
| product_id | TotalAmount |
|------------|-------------|
| 5 | 300 |
| 10 | 400 |
答案 1 :(得分:0)
将GROUP BY与SUM一起使用COUNT:
SELECT product_id, SUM(amount) AS TotalAmount, COUNT(product_id) as Count
FROM tablename
GROUP BY product_id;
结果:
| product_id | TotalAmount | Count |
|------------|-------------|-------|
| 5 | 300 | 3 |
| 10 | 400 | 4 |
答案 2 :(得分:0)
使用GROUP_BY product_id和sum
SELECT product_id, SUM(amount) AS TotalAmount
FROM tablename
GROUP BY product_id;