选择项目和具有相同表格的项目总和

时间:2014-04-25 12:05:41

标签: sql sum

我有像

这样的表格项目
  id  |  name | amount
 -----+-------------
    1 | item1 | 3
    2 | item2 | 6
    3 | item2 | 7
    4 | item2 | 6
    5 | item3 | 3
    6 | item3 | 2

我如何能够获得所有项目的总和,如

  n   |  name | sum
 -----+-------------
    1 | item1 | 3
    2 | item2 | 19
    3 | item3 | 5

我试过这个,但它不起作用

SELECT a.name FROM item a
JOIN
( SELECT SUM( amount ), name
  FROM item group by id
) AS b
ON b.name= a.name

1 个答案:

答案 0 :(得分:5)

你的要求对你想做的事情很奇怪......你应该这样做:

SELECT I.name, SUM(I.amount) 
FROM item I
WHERE 1
GROUP BY I.name
ORDER BY I.name ASC ;

如果您想n

SET @num=0;
SELECT @num:=@num+1 AS n, I.name AS name, SUM(I.amount) AS sum
FROM item I
WHERE 1
GROUP BY I.name
ORDER BY I.name ASC ;

如果您想订购namen,则需要选择2个:

SET @num=0;
SELECT @num:=@num+1 AS n, I.name AS name, I.sum AS sum
FROM (SELECT I.name AS name, SUM(I.amount) AS sum
      FROM item I
      WHERE 1
      GROUP BY I.name
      ORDER BY I.name ASC) AS I
WHERE 1 ;