简体   繁体   English

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

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

cat use min as condition 猫用min作为条件

the where statement is where it breaks but i cant fix it where语句是在哪里打破但我无法解决它

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

Having + sub-query 有+子查询

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
                          )

Another option, but with this solution in case of ex-aequo only first category is removed: 另一种选择,但在以前只有第一类的情况下使用此解决方案被删除:

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

You could use common table expressions here, eg: 您可以在这里使用公用表表达式,例如:

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