我确定这可能是我遗失的简单东西,但是我正在尝试执行一个MySQL查询,该查询对某行中每个项目的出现进行计数,并返回具有整个行的结果,并按count排序。
例如,我有这些条目的行:
Agriculture
Energy
Energy
Environment
Agriculture
Mining
Energy
我希望我的查询返回给我:
Energy
Energy
Energy
Agriculture
Agriculture
Environment
Mining
我正在尝试:
SELECT `companyname`, `id`, `location`,`industry`, COUNT(`industry`) AS `industry_occurrence`
FROM atl3_atl_testimonials
WHERE state ='1'
ORDER BY industry_occurrence
但是,它仅返回第一个“能量”结果,而不是按出现顺序返回的所有结果。我应该改变什么?
最佳答案
希望您在这里正在寻找这样的一个。
SELECT `companyname`, `id`, `location`,
a.industry, cnt AS `industry_occurrence`
FROM atl3_atl_testimonials a,
(SELECT COUNT(`industry`) cnt, `industry`
FROM atl3_atl_testimonials
Group by industry) f
WHERE state ='1'
AND f.industry = a.industry
ORDER BY cnt desc