MySQL Max Count没有Order By

时间:2011-06-15 12:50:29

标签: mysql count max

我有以下MySQL行:

SELECT age, count(*) AS total FROM pacient WHERE age BETWEEN 20 AND 40 GROUP BY age ORDER BY age我需要添加一个额外的列,它只显示每行的计数(*)的最大值。例如:

13 2 7
18 2 7
23 5 7
24 7 7
26 6 7
32 3 7
38 1 7
41 1 7
46 4 7

这将是3列,第3列显示7,因为7是第二列中计数(*)的最高数字。

4 个答案:

答案 0 :(得分:4)

这里是解决方案:

select age,
    count(*),
    (select max(c) from 
        (select count(*) as c from pacient where age between 20 and 40 group by age) as x) as t 
from pacient 
where age between 20 and 40 
group by age 
order by age;

答案 1 :(得分:1)

您是否尝试使用其他查询包装查询?

之类的东西
SELECT A.age, A.total, MAX(A.total) as max_value FROM (
    SELECT age, count(*) AS total 
    FROM pacient
    WHERE age BETWEEN 20 AND 40 
    GROUP BY age ORDER BY age) as A
GROUP BY A.age, A.total

答案 2 :(得分:1)

select 
      p.Age,
      count(*)  CountPerAge,
      max(ar.AllRecs) AllRecs
   from
      pacient p,
      ( select count(*) AllRecs 
           from pacient p2
           where p2.age between 20 and 40 ) ar
   where 
      p.age between 20 and 40
   group by
      p.age

通过连接到没有连接条件的第二个“subselect”,它将给出一个笛卡尔结果...因为它是一个没有group by的计数,它将始终返回一个记录,因此将连接到所有否则为年龄行。值的MAX()没有问题,因为它只是按原样返回的唯一记录。

答案 3 :(得分:0)

使用SQL VIEWS而不是使用子查询总是好的。因为VIEW已经编译了结果。

CREATE VIEW subqueryView 
    SELECT age, count(*) AS total 
    FROM pacient
    WHERE age BETWEEN 20 AND 40 
    GROUP BY age ORDER BY age

SELECT A.age, A.total, MAX(A.total) as max_value FROM (SELECT FROM subqueryView) as A
GROUP BY A.age, A.total