How to get multiple counts with one SQL query?

后端 未结 9 2219
清酒与你
清酒与你 2020-11-22 14:03

I am wondering how to write this query.

I know this actual syntax is bogus, but it will help you understand what I am wanting. I need it in this format, because it i

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 14:21

    One way which works for sure

    SELECT a.distributor_id,
        (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
        (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
        (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
    FROM (SELECT DISTINCT distributor_id FROM myTable) a ;
    

    EDIT:
    See @KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for @Taryn♦'s answer. I'm leaving this so people can understand their options.

提交回复
热议问题