如何计算MySQL中的项目数?

时间:2011-06-01 03:11:47

标签: mysql sql

在示例中更好地解释。

我在MySQL中有以下数据

   Name   address   age    
   John1   33 St    20    
   John2   22 St    21
   John3   44 St    20
   John4   55 St    21
   John6   44 St    20
   John5   66 St    35

我想获得基于年龄的计数行列表。但是有可能让最后一行与每个计数相关联。实施例

   Name   address   age   Count 
   John6   44 St    20      3
   John4   55 St    21      2
   John5   66 St    35      1

2 个答案:

答案 0 :(得分:1)

查看GROUP BY

的语法
SELECT *, count(*) as Count FROM tableName GROUP BY age;

更新

假设您决定添加一个排序列,例如日期时间:

   Name   address   age created   
   John1   33 St    20  2011-04-01 10:00:00
   John2   22 St    21  2011-04-01 09:00:03
   John3   44 St    20  2011-04-01 07:00:20
   John4   55 St    21  2011-04-01 08:45:01
   John6   44 St    20  2011-04-01 13:00:00
   John5   66 St    35  2011-04-01 12:00:40

然后你就可以完成你的最终目标:

  SELECT *, count(*) as Count
    FROM ( SELECT * FROM tableName ORDER BY created DESC ) as newTable
GROUP BY age;

您必须使用嵌套选择,否则 ORDER BY之后将应用GROUP BY

答案 1 :(得分:0)

斯蒂芬指出,你需要做一个嵌套的选择,但反过来说:

SELECT 
    u.Name,u.Address, u.age, u.NumCount
FROM (SELECT Name, Address, age, count(age) from users group by age) as u
ORDER BY u.NumCount desc