[英]MySQL - Sort results in descending order of overall count
I have a table as below 我有一张桌子,如下
year -------- org ------- name ---------- category -------- points 年--------组织-------名称----------类别--------积分
2005 -------- ABC ------- N1 ---------- CAT1 -------- 10 2005 -------- ABC ------- N1 ---------- CAT1 -------- 10
2006 -------- DEF ------- N2 ---------- CAT2 -------- 5 2006 -------- DEF ------- N2 ---------- CAT2 -------- 5
etc 等等
Primary key in this table is (year, org, name) 该表中的主键是(年,组织,名称)
I need an output as below 我需要如下输出
org ------- category ------ points (sorted in descending order of overall points of org) org -------类别------点(按org总点的降序排列)
DEF ------- CAT1 ------ 1000 DEF ------- CAT1 ------ 1000
DEF ------- CAT2 ------ 5000 DEF ------- CAT2 ------ 5000
DEF ------- CAT3 ------ 2000 DEF ------- CAT3 ------ 2000
ABC ------- CAT1 ------ 6000 ABC ------- CAT1 ------ 6000
ABC ------- CAT2 ------ 100 ABC ------- CAT2 ------ 100
ABC ------- CAT3 ------ 50 ABC ------- CAT3 ------ 50
DEF score is 8000 which is higher than the score of ABC which is 6150. So appears at the top of the expected output DEF得分为8000,高于ABC得分为6150。因此出现在预期输出的顶部
I wrote a select statement as below 我写了如下的选择语句
select org, cat, count(cat) from table where year=2006 group by org, cat order by org 从表中选择org,cat,count(cat),其中year = 2006按org分组,按cat分组
I get the result ordered by org but I am unable to get the output sorted in descending order of overall count of points of every type of org 我按组织将结果排序,但无法按每种组织的总点数的降序对输出进行排序
Any help is much appreciated. 任何帮助深表感谢。 Thanks - Praveen 谢谢-Praveen
在查询末尾,您使用desc关键字,这将有助于您
Use a JOIN to group the org
alone, and get the SUM
of all the counts for each group: 使用JOIN将org
单独分组,并获得每个组的所有计数的SUM
:
SELECT t.org, t.cat, count(t.cat)
FROM table t JOIN (
SELECT org, count(cat) SumCount
FROM table
WHERE year=2006
GROUP BY org
) tg ON t.org = tg.org
WHERE t.year = 2006
GROUP BY t.org, t.cat
ORDER BY MAX(rs.SumCount), t.org DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.