简体   繁体   中英

mysql group query by name and order by id and limit by id

I have a table like this

id   name   amount
 1   fish    120
 1   meat    230
 2   meat    110
 2   fish    78
 1   salad   50
 3   meat    103
 3   salad    22
 2   salad    34

i want to write a query that will group the names and sum their amount but it should limit to the first two id, thus group items by name and sum each matching name... this should limit it to the first two id. that is id 1 and 2 only. leaving id 3. Note. the ID is a foreign key from another table.

This is what i have tried. but it's not working

select name, sum(amount) from table1 group by amount, id order by id limit 2

this only outputs 2 results after doing the computation

name   amount
fish   198
meat   443

I am expecting something like this

name   amount
fish   198
meat   340
salad  84

Add the amount of items with id of only 1 and two and group them by name

select name, sum(amount)
from
  (SELECT id, name, amount,
       CASE WHEN @name=name THEN @rown:=@rown+1 ELSE @rown:=0 END as rn,
       @name:=name 
  FROM table1, (select @rown:=0, @name:='') s
  ORDER BY name, id
  ) sub
where rn<=1
group by name

output

fish    198
meat    340
salad   84
SELECT name, sum(amount) 
  FROM table1 
 WHERE id <= 2
 GROUP BY name
 ORDER BY name

You don't want to limit to total output but you want to limit it before it makes sum so to do that you can use subqueries.

select t1.name, sum(t1.amount)
from table1 t1 join
     (select tt1.id
      from table1 tt1
      group by id
      order by id
      limit 2
     ) t2
     on t1.id = t2.id
group by t1.name;

Working example link

Result :

name    sum(t1.amount)

fish    198

meat    340

salad   84

What are the first two ids? If I assume you mean "globally", then:

select t1.name, sum(t1.amount)
from table1 t1 join
     (select tt1.id
      from table1 tt1
      group by id
      order by id
      limit 2
     ) tt1
     on t1.id = tt1.id
group by t1.name;

Remove the LIMIT and only GROUP BY the name

SELECT Name, SUM(amount) AS Amount
FROM table1 
GROUP BY name 
ORDER BY id

Output

Name    Amount
fish    198
meat    443
salad   106

SQL Fiddle: http://sqlfiddle.com/#!9/2a8868/7/0

I think you can use something like this:

SELECT B.NAME, SUM(B.AMOUNT) AS AMOUNT
FROM (
      SELECT a.* ,
      @r:= CASE WHEN @g = a.NAME THEN @r+1 ELSE 1 END consecutive,
      @g:= a.NAME g    
      FROM DISHES a
      CROSS JOIN (SELECT @g:='', @r:=1 ) t1
      ORDER BY A.NAME, A.id
      ) B
      WHERE B.consecutive<=2
      GROUP BY B.NAME;

Output:

NAME    AMOUNT
fish    198
meat    340
salad   84

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM