从下面的表格中,如何选择删除分类最多的用户以及已删除分类的数量?在这里:6 =已删除。我正在使用mySql。
"userid" "classStatus"
"1" "6"
"1" "6"
"2" "0"
"2" "6"
"3" "0"
"3" "0"
所以在这种情况下,输出将是:
"userid" "numberofClassifieds"
"1" "2"
"2" "1"
我对基本的sql语句没问题,但看不到找到办法。
select max(count(classStatus)) as t, userid as u from testtops where classStatus=6;
答案 0 :(得分:1)
这将选择至少有一个已删除的类字段的所有用户,它将显示所有类字段的数量和所有已删除类字段的数量:
SELECT
userid,
count(*) as numberofClassifieds,
sum(classStatus=6) as numberofDeletedClassfields
FROM
your_table
GROUP BY userid
HAVING numberofDeletedClassfields>0
ORDER BY numberofDeletedClassfields DESC
编辑:这是一种使用连接的替代方案,它看起来不像其他查询那么优雅,但它的速度要快得多:
SELECT dc.userid, c.numberofClassfields, dc.numberofDeletedClassfields
FROM
(select userid, count(*) as numberofDeletedClassfields
from your_table
where classStatus = 6
group by userid
having count(*)>0) dc
INNER JOIN
(select userid, count(*) as numberofClassfields
from your_table
group by userid) c
on dc.userid=c.userid
ORDER BY dc.numberofDeletedClassfields desc
EDIT2:无论如何,如果您正在寻找已删除的Classfields的最大数量,那么您可以使用它:
select max(numberofDeletedClassfields)
from (
select count(*) as numberofDeletedClassfields
from your_table
where classStatus = 6
group by userid) s
答案 1 :(得分:0)
您的查询中缺少GROUP BY
,
SELECT userid, COUNT(*) NumberOfClassified
FROM tableName
WHERE classStatus = 6
GROUP BY userID
ORDER BY NumberOfClassified DESC
答案 2 :(得分:0)
select count(*) as numberofClassifieds, userid from testtops
where classStatus=6
group by userid
试试这个
答案 3 :(得分:0)
SELECT userid, COUNT(*) NumberOfClassified
FROM tableName WHERE classStatus = 6
GROUP BY userID
ORDER BY NumberOfClassified DESC limit 1
答案 4 :(得分:0)
请尝试下面的查询
SELECT `userid` , count(*) AS numberofClassifieds FROM `testtops` where `classStatus` = 6 group by `userid` order by numberofClassifieds DESC
感谢