简体   繁体   English

在SQL上计算类别中的不同项目

[英]Counting distinct items within a category on SQL

I need to compose a SQL statement as follows: 我需要编写一个SQL语句,如下所示:

I have a table with many items, each item having a category. 我有一个包含许多项目的表格,每个项目都有一个类别。 In total there are 3 categories. 总共有3个类别。

I need to select the DISTINCT categories and then order them by number of items within each category. 我需要选择DISTINCT类别,然后按每个类别中的项目数量排序。

Would this be a good way? 这会是一个好方法吗? Or too slow? 还是太慢了?

SELECT DISTINCT category, count(*) AS counter
FROM item_descr
GROUP BY category
ORDER BY counter DESC

The DISTINCT is not needed since you are using GROUP BY category : 由于您使用GROUP BY category因此不需要DISTINCT

SELECT category, count(*) AS counter
FROM item_descr
GROUP BY category
ORDER BY counter DESC

The GROUP BY is doing what you want. GROUP BY正在做你想要的。 DISTINCT is redundant. DISTINCT是多余的。

如果要获得良好的性能(尤其是在较大的表上),则在类别上建立索引非常重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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