显示不包括最小值和最大值的列数
Posted
技术标签:
【中文标题】显示不包括最小值和最大值的列数【英文标题】:Display count of column excluding min and max values 【发布时间】:2021-01-13 12:47:28 【问题描述】:我想在下表(朋友)中计算一个活动的唯一出现次数。然后,我想打印它们的出现不是所有出现的最大值或最小值的活动。
***ID/Name/Activity***
1/James/Horse Riding
2/Eric/Eating
3/Sean/Eating
4/John/Horse Riding
5/Chris/Eating
6/Jessica/Paying
例如:
Horse Riding occur 140 times
Playing occurs 170 times
Eating occurs 120 times
Walking occurs 150 times
Running occurs 200 times
这里出现最多的是 Running,出现了 200 次,这里出现的最少的是 Eating,出现了 120 次。
因此,我想显示
Horse Riding
Playing
Walking
没有特别的顺序。
这是我目前拥有的代码,但我不断收到语法错误。当我没有收到语法错误时,我会收到“每个派生表都必须有自己的别名错误”。我是 SQL 新手,所以我很感激我能得到的任何建议。
SELECT ACTIVITY, count(ACTIVITY) as Occurences FROM FRIENDS,
(SELECT MAX(Occur) AS Ma,MIN(Occur) AS Mi FROM (SELECT ACTIVITY, count(ACTIVITY) as Occur
FROM FRIENDS GROUP by City)) as T
GROUP BY City HAVING Occurences!=T.Ma AND Occurences!=T.Mi ORDER BY Occurences DESC
【问题讨论】:
今日提示:切换到现代、明确的JOIN
语法!更容易编写(没有错误),更容易阅读维护,如果需要更容易转换为外连接!
请看Why should I provide an MCRE for what seems to me to be a very simple SQL query
【参考方案1】:
在 mysql 8.0 中,您可以使用聚合和窗口函数来做到这一点:
select *
from (
select activity, count(*) cnt,
rank() over(order by count(*)) rn_asc,
rank() over(order by count(*) desc) rn_desc
from mytable
group by activity
) t
where rn_asc > 1 and rn_desc > 1
子查询计算每个活动的出现次数,并按升序和降序排列它们。剩下要做的就是排除顶部和底部的记录。如果有顶部关系(或底部),则查询将它们逐出。
在早期版本中,选项是having
子句:
select activity, count(*) cnt
from mytable t
group by activty
having count(*) > (select count(*) from mytable group by activity order by count(*) limit 1)
and count(*) < (select count(*) from mytable group by activity order by count(*) desc limit 1)
【讨论】:
以上是关于显示不包括最小值和最大值的列数的主要内容,如果未能解决你的问题,请参考以下文章