首页 > 解决方案 > Mysql Limit By sum of count

问题描述

我在 mysql 表 id、状态和计数中有 3 列字段我想获得状态组和具有不同 id 值的计数总和示例如下

id - status - count

1 - test1   -   1
1 - test1   -   1
1 - test2   -   1
1 - zer1   -    0
2 - exam1   -   1
2 - exam1   -   1
2 - zer2   -    0
2 - exam2   -   1
3 - mit1    -   1
3 - mit2    -   1
3 - zer3   -    0
4 - term1   -   1

我想要如下结果

id - status - count
1 - test1   -   2
2 - exam1   -   2
3 - mit1    -   1
4 - term1   -   1

我尝试了以下查询的结果,但我没有得到结果

SELECT id,status,sum(count) as count FROM `test` where count=1 group by status order by id

对于上述查询,我​​得到以下结果

id - status - count
 1  test1   2
 2  exam1   2
 2  exam2   1
 3  mit1    1
 3  mit2    1
 4  term1   1

我无法找到正确的查询来删除重复的 ID 并按计数总和排序。请指导我得到结果。

标签: mysqlsql

解决方案


您可以在此处使用多个查询,例如:

    Select distinct id from 
    (SELECT id,status,
   sum(count) as count 
   FROM `test` where count=1 group by status order by id 
    )

推荐阅读