Domanda

i have table item like

  id  |  name | amount
 -----+-------------
    1 | item1 | 3
    2 | item2 | 6
    3 | item2 | 7
    4 | item2 | 6
    5 | item3 | 3
    6 | item3 | 2

how i can get all with sum of items like

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

i have try this but it doesnt works

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

Soluzione

You request is strange for what you want to do... You should just do :

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

If you want to have 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 ;

If you want to order name AND n, you have to do 2 selects :

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 ;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top