简体   繁体   English

如何计算所有COUNT的总和?

[英]How to take SUM of all COUNTs?

I am new to mysql . 我是mysql新手。

I have a query to get count from different tables and it works okay. 我有一个查询要从不同的表中获取计数,它工作正常。 But, now I want to club all 3 query COUNT into 1 like SUM (COUNT1, COUNT2, COUNT3) 但是,现在我想将所有3个查询COUNT合并为1,例如SUM(COUNT1,COUNT2,COUNT3)

select COUNT(*) as count1, 0 as count2, 0 as count3 from table1 
UNION ALL 
select 0 as count1, COUNT(*) as count2, 0 as count3 from table2 
UNION ALL 
select 0 as count1, 0 as count2, COUNT(*) as count3 from table3

Eg count1 = 10, count2 = 20 and count3 = 15 例如count1 = 10,count2 = 20和count3 = 15

Then, I want to get sum = 45 然后,我想求和= 45

You can put the UNION in a subquery and then SUM() the counts. 您可以将UNION放在子查询中,然后将SUM()计数。 But there's no need to put them in separate columns in each unioned query. 但是,无需在每个联合查询中将它们放在单独的列中。

SELECT SUM(count) AS total
FROM (
    SELECT COUNT(*) AS count FROM table1
    UNION ALL
    SELECT COUNT(*) AS count FROM table2
    UNION ALL
    SELECT COUNT(*) AS count FROM table3
) AS subquery

to get sum of all counts from you tables you can write a query as 要从表中获取所有计数的总和,可以编写查询为

select 
(select COUNT(*) from table1) +
(select COUNT(*) from table2) +
(select COUNT(*) from table3) as total

Following your approach, you can wrap unioined query in as sub select and then apply sum on the results 按照您的方法,您可以将非限定查询包装为子选择,然后将总和应用于结果

SELECT SUM(count1) + SUM(count2) + SUM(count3) total
FROM (
    SELECT COUNT(*) AS count1, 0 AS count2, 0 AS count3 FROM table1 
    UNION ALL 
    SELECT 0 AS count1, COUNT(*) AS count2, 0 AS count3 FROM table2
    UNION ALL 
    SELECT 0 AS count1, 0 AS count2, COUNT(*) AS count3 FROM table3
) t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM