【问题标题】:Combining several similar queries结合几个相似的查询
【发布时间】:2021-02-18 15:51:48
【问题描述】:

如何将这三个查询合二为一?

SELECT COUNT(*) 
FROM Users 
WHERE (SELECT COUNT(*) FROM Posts WHERE Posts.OwnerUserId = Users.Id) < 10;

SELECT COUNT(*) 
FROM Users 
WHERE (SELECT COUNT(*) FROM Posts WHERE Posts.OwnerUserId = Users.Id) BETWEEN 10 AND 20;

SELECT COUNT(*) 
FROM Users 
WHERE (SELECT COUNT(*) FROM Posts WHERE Posts.OwnerUserId = Users.Id) > 20;

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。

标签: mysql sql select count subquery


【解决方案1】:

如果我没听错的话,您可以使用两个级别的聚合。以下查询将每个存储桶放在单独的行中:

select
    case 
        when cnt < 10 then '< 10'
        when cnt < 20 then '10-20'
        else '> 20'
    end as bucket,
    count(*) cnt
from (
    select count(p.owneruserid) cnt
    from users u
    left join posts p on p.owneruserid = u.id
    group by u.id
) t
group by case 
    when cnt < 10 then '< 10'
    when cnt < 20 then '10-20'
    else '> 20'
end 

或者您可以在同一行获得所有三个计数,如下所示:

select
    sum(case when cnt < 10 then 1 else 0 end) as cnt_less_than_10,
    sum(case when cnt >= 10 and cnt < 20 then 1 else 0 end) as cnt_10_to_20,
    sum(case when cnt > 20 then 1 else 0 end) as cnt_more_than_20
from (
    select count(*) cnt
    from users u
    inner join posts p on p.owneruserid = u.id
    group by u.id
) t

【讨论】:

  • 是的,太好了,谢谢!据我了解,您的比较是错误的,因为还包括 20。您的第一个查询在修复后给出了正确的计数,但第二个查询由于某种原因在 cnt_less_than_10 上撒谎……顺便说一句,它自己给出了不同的结果。为什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多