2017-03-05 67 views
0

例如,如果我们去w3schools计数不包括最大分钟数

并把

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

enter image description here

但我真正想要的是排除最大和最小occurances(忽略最大和最小硬编码的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的情况下获得所需输出的方式是什么?

回答

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 
+1

谢谢!这是我正在寻找的答案:) –

+1

欢迎:) – jophab

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和订购,但我更喜欢这个