简体   繁体   中英

MySQL Arbitrary Ordering Of Group By

I have a SQL query the looks like

SELECT Fruit, COUNT(*) FROM Table1 GROUP BY Fruit

It Returns

Grape 8
Apple 2
Peach 9
Orange 6
Banana 5

I do NOT wish to sort alphabetically.

I want it in this order

Banana
Apple
Orange
Peach
Grape

I cant seem to get they Syntax right on a case stamens.....Help!

You could use FIELD() function:

SELECT Fruit, COUNT(*)
FROM Table1
GROUP BY Fruit
ORDER BY FIELD(Fruit, 'Banana','Apple','Orange','Peach','Grape')

You can use a CASE in an ORDER BY clause to put the data in an order that you want:

SELECT Fruit, COUNT(*) Total
FROM Table1 
GROUP BY Fruit
order by 
  case fruit 
    when 'banana' then 1
    when 'apple' then 2
    when 'orange' then 3
    when 'peach' then 4
    when 'grape' then 5 
    else 6 end;

See SQL Fiddle with Demo

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