说我有一张包含以下记录的表:
+----+-------+--------+
| ID | Type | Item |
+----+-------+--------+
| 1 | food | apple |
| 2 | food | apple |
| 3 | food | orange |
| 4 | food | apple |
| 5 | food | banana |
| 6 | food | banana |
| 7 | drink | cola |
| 8 | drink | water |
| 9 | food | banana |
| 10 | food | apple |
+----+-------+--------+
如何构造一个返回单个列列表的查询,这些列表只有Type:food,并且只包含在表中多次出现的每个项目的一次出现 - 最后按顺序排序它们出现在表格中的次数?
因此上表的结果如下:
-apple (4 occurrences)
-banana (3 occurrences)
-orange (1 occurrence)
感谢。
答案 0 :(得分:2)
此查询将执行此操作!
select count(*) as Total ,item from tbl
where type='food'
group by item order by Total desc;
同时查看小提琴演示: http://sqlfiddle.com/#!2/5b3c6/3
答案 1 :(得分:1)
试试这个:
select Item, count(Item) as COUNT
FROM TableName
WHERE Type='food'
GROUP BY Item
ORDER BY COUNT DESC
结果:
ITEM COUNT
apple 4
banana 3
orange 1
请参阅SQL Fiddle中的结果。