计数排除最大发生次数

时间:2017-03-05 08:50:35

标签: mysql sql database count

例如。如果我们转到w3schools

然后把

SELECT City, count(City) as Occurrences
FROM Customers 
GROUP by City
ORDER BY count(City) DESC

enter image description here

但我真正想要的是排除最大和最小出现次数(忽略最大和最小值的硬编码6和1值),例如

SELECT City, count(City) as Occurances
FROM Customers 
GROUP by City
HAVING count(City) != 6 AND count(City) != 1
ORDER BY count(City) DESC

enter image description here

如果没有硬编码6和1,获得所需输出的方法是什么?

2 个答案:

答案 0 :(得分:2)

你可以试试这个

select c1.city, c1.cnt from (
select city, count(*) cnt from customers c
group by city
) c1 inner join 
(select max(cnt) max_cnt, min(cnt) min_Cnt from (
select city, count(*) cnt from customers c
group by city
)) c2
on c1.cnt!=c2.max_cnt and c1.cnt!=c2.min_cnt
;

因为MySQL没有OVER..PARTITION BY函数,这可能很有用。 另一种方法可能是rownums和订购,但我更喜欢这个

答案 1 :(得分:1)

试试这个

SELECT City, count(City) as Occurences FROM Customers,
(SELECT MAX(Occur) AS Ma,MIN(Occur) AS Mi FROM (SELECT City, count(City) as Occur
FROM Customers GROUP by City)) as T 
GROUP BY City HAVING Occurences!=T.Ma AND Occurences!=T.Mi ORDER BY Occurences DESC