How to get multiple counts with one SQL query?

后端 未结 9 2055
清酒与你
清酒与你 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:04

    Based on Bluefeet's accepted response with an added nuance using OVER():

    SELECT distributor_id,
        COUNT(*) total,
        SUM(case when level = 'exec' then 1 else 0 end) OVER() ExecCount,
        SUM(case when level = 'personal' then 1 else 0 end) OVER () PersonalCount
    FROM yourtable
    GROUP BY distributor_id
    

    Using OVER() with nothing in the () will give you the total count for the whole dataset.

    0 讨论(0)
  • 2020-11-22 14:05
    SELECT 
        distributor_id, 
        COUNT(*) AS TOTAL, 
        COUNT(IF(level='exec',1,null)),
        COUNT(IF(level='personal',1,null))
    FROM sometable;
    

    COUNT only counts non null values and the DECODE will return non null value 1 only if your condition is satisfied.

    0 讨论(0)
  • 2020-11-22 14:11

    For MySQL, this can be shortened to:

    SELECT distributor_id,
        COUNT(*) total,
        SUM(level = 'exec') ExecCount,
        SUM(level = 'personal') PersonalCount
    FROM yourtable
    GROUP BY distributor_id
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 14:24

    Well, if you must have it all in one query, you could do a union:

    SELECT distributor_id, COUNT() FROM ... UNION
    SELECT COUNT() AS EXEC_COUNT FROM ... WHERE level = 'exec' UNION
    SELECT COUNT(*) AS PERSONAL_COUNT FROM ... WHERE level = 'personal';
    

    Or, if you can do after processing:

    SELECT distributor_id, COUNT(*) FROM ... GROUP BY level;
    

    You will get the count for each level and need to sum them all up to get the total.

    0 讨论(0)
  • 2020-11-22 14:24

    I think this can also works for you select count(*) as anc,(select count(*) from Patient where sex='F')as patientF,(select count(*) from Patient where sex='M') as patientM from anc

    and also you can select and count related tables like this select count(*) as anc,(select count(*) from Patient where Patient.Id=anc.PatientId)as patientF,(select count(*) from Patient where sex='M') as patientM from anc

    0 讨论(0)
提交回复
热议问题