two SQL COUNT() queries?

前端 未结 5 441
时光取名叫无心
时光取名叫无心 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:39

    In Sql Server or MySQL, you can do that with a CASE statement:

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

    Edit: This also works if you use a JOIN in the condition:

    select 
        count(*) as TotalCount,
        sum(case when {conditions} then 1 else 0 end) as QualifiedCount
    from MyTable t
    left join MyChair c on c.TableId = t.Id
    group by t.id, t.[othercolums]
    

    The GROUP BY is there to ensure you only find one row from the main table.

提交回复
热议问题