SQL:查找每个类别的项目总数并排序结果

时间:2019-03-27 02:50:00

标签: mysql sql count

我有一个称为字段的下表:

Category       |     Industry     |  Company
Research             Science         Biolite
Retail               Healthcare      The Vitamin Shop
Crafts               Stationery      Art Centre
Research             Science         GeneSys
Retail               Healthcare      Live Healthy
Crafts               Stationery      Typewrite Pens

我希望能够找到每个行业的公司总数,然后按类别然后按行业排序结果。 (例如,对于科学公司,将有2家公司;对于医疗保健公司,将有2家公司;对于文具公司,也将有2家公司)。输出应如下所示(无序):

Category  |  Industry    |   Number
Research     Science         2
Retail       Healthcare      2
Crafts       Stationery      2

我有以下查询:

select t1.Category, t1.Industry, t2.Number from Field t1
inner join (
select Industry, count(*) as Number from Field
group by Industry
) t2
on t1.Industry = t2.Industry;

但是,在结果表的“行业”列中,显示了重复的行业(例如,科学出现了两次)。我怎样才能使“行业”列只显示每个行业一次?

1 个答案:

答案 0 :(得分:2)

按类别和行业分组:

select Category,Industry, count(*) as 'Number'
from Field
group by Category,Industry