two SQL COUNT() queries?

前端 未结 5 432
时光取名叫无心
时光取名叫无心 2020-12-16 19:03

I want to count both the total # of records in a table, and the total # of records that match certain conditions. I can do these with two separate queries:

S         


        
5条回答
  •  独厮守ぢ
    2020-12-16 19:42

    One way is to join the table against itself:

    select
       count(*) as TotalCount,
       count(s.id) as QualifiedCount
    from
       MyTable a
    left join
       MyTable s on s.id = a.id and {some conditions}
    

    Another way is to use subqueries:

    select
       (select count(*) from Mytable) as TotalCount,
       (select count(*) from Mytable where {some conditions}) as QualifiedCount
    

    Or you can put the conditions in a case:

    select
       count(*) as TotalCount,
       sum(case when {some conditions} then 1 else 0 end) as QualifiedCount
    from
       MyTable
    

    Related:

    SQL Combining several SELECT results

提交回复
热议问题