繁体   English   中英

如何在SQL查询中使用min作为条件

[英]how to use min as a condition in sql query

猫用min作为条件

where语句是在哪里打破但我无法解决它

select category, count(*) as number_of_cats
from books
where number_of_cats > min(number_of_cats)
group by category
order by category;

有+子查询

select category, count(*) as number_of_books
from books
group by category
having count(*) >     -- check the one whose count is STRICTLY greater then minimum
                      (  select min (st.t) -- find the minimum of all categories
                         from
                         ( select count(*) as t --find the count for all categories
                           from books
                           group by category
                                    ) st -- an alias to avoid parsing errors
                          )

另一种选择,但在以前只有第一类的情况下使用此解决方案被删除:

select select category, count(*) as number_of_books
    from books
    where category not in (select bb.category 
                           from books bb
                           group by bb.category 
                           order by count(*) asc
                           limit 1)
    group by category

您可以在这里使用公用表表达式,例如:

WITH CategoryCount AS (
    SELECT 
        category, 
        COUNT(*) AS number_of_books
    FROM
        books
    GROUP BY 
        category),
MinBooks AS (
    SELECT
        MIN(number_of_books) AS min_number_of_books
    FROM
        CategoryCount)
SELECT
    cc.*
FROM
    CategoryCount cc
    CROSS JOIN MinBooks m
WHERE
    cc.number_of_books > m.min_number_of_books;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM