我写了一个查询:
SELECT `name` , COUNT( * ) FROM `daily` GROUP BY `Name`
UNION
SELECT `name` , COUNT( * ) FROM `monday` GROUP BY `Name`
我收到了这个结果
Name | Count(*)
-------------------
Person 1 | 10 |
Person 2 | 05 |
Person 3 | 00 |
Person 1 | 08 |
Person 2 | 10 |
我只想得到这个结果:
Name | Count(*)
-------------------
Person 1 | 18 |
Person 2 | 15 |
Person 3 | 00 |
我想将两个表中的两个值添加到相同的“名称”中。我在这里使用什么连接命令?
答案 0 :(得分:1)
未经测试
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;
希望这有效:)
答案 1 :(得分:1)
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]
答案 2 :(得分:0)
您希望在聚合之前执行union
:
select name, count(*)
from (select name from daily union all select name from monday) t
group by name;
你也可以预先聚合这些值,虽然我不确定MySQL中是否有性能提升来执行此操作:
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;