简体   繁体   中英

SQL Adding the number of occurrences from different tables

I have written a query:

SELECT  `name` , COUNT( * ) FROM  `daily` GROUP BY  `Name` 
UNION 
SELECT  `name` , COUNT( * ) FROM  `monday` GROUP BY  `Name` 

I am getting this result

Name  |  Count(*)
-------------------

Person 1 | 10 |

Person 2 | 05 |

Person 3 | 00 |

Person 1 | 08 |

Person 2 | 10 |

I simply want to get this result:

Name  |  Count(*)
-------------------
Person 1 | 18 |

Person 2 | 15 |

Person 3 | 00 |

I want to add the two values from the two tables against the same 'name'. What join command do I use here ?

This is not tested

select name, SUM(total)
from ( 
  SELECT name , COUNT( * ) as total
  FROM daily 
  GROUP BY Name 

  UNION 

  SELECT name ,COUNT( * ) as total
  FROM monday 
  GROUP BY Name 
) 
GROUP BY name;

Hope this works :)

SELECT [name], Sum(NameCount) as [Count] 
FROM (SELECT [name] , COUNT(*) AS NameCount
    FROM daily GROUP BY [name] 
  UNION ALL SELECT [name] , COUNT(*) AS NameCount 
    FROM monday GROUP BY [name] ) AS Counts
GROUP BY [name]

You want to do the union before the aggregation:

select name, count(*)
from (select name from daily union all select name from monday) t
group by name;

You can also pre-aggregate the values, although I'm not sure if there is a performance gain in MySQL to do this:

select name, sum(cnt)
from ((select name, count(*) as cnt from daily group by name)
      union all
      (select name, count(*) as cnt from monday group by name)
     ) t
group by name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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