[英]SQL: detecting differences in sums between two tables?
It seems simple enough: I have two votes and I want to see which states have different numbers of votes. 看起来很简单:我有两票,我想看看哪些州有不同的票数。 Individually, it's very easy:
单独来说,这很容易:
select state, sum(votes) from votes_a group by state;
select state, sum(votes) from votes_b group by state;
How do I query for something like state, votes_a, votes_b
for the states that have different results? 如何针对具有不同结果的状态查询
state, votes_a, votes_b
之类的内容?
Try a join: 尝试加入:
SELECT
totals_a.state,
totals_a.total_votes,
totals_b.total_votes
FROM
(
SELECT state, SUM(votes) AS total_votes
FROM votes_a
GROUP BY state
) AS totals_a
JOIN
(
SELECT state, SUM(votes) AS total_votes
FROM votes_b
GROUP BY state
) AS totals_b
ON totals_a.state = totals_b.state
WHERE totals_a.total_votes <> totals_b.total_votes
Note that this will miss states which received zero votes in one of the tables. 请注意,这将错过在其中一个表中收到零票的州。 To fix this you could use a FULL OUTER JOIN (assuming your database supports this feature) and check for NULLs.
要解决此问题,您可以使用FULL OUTER JOIN(假设您的数据库支持此功能)并检查NULL。
Try this ... 尝试这个 ...
select state, sum(votes_a), sum(votes_b)
from (select state, sum(votes) votes_a, 0 votes_b
from votes_a
group by state) tbl_a
(select state, 0 votes_a, sum(votes) votes_b
from votes_b
group by state ) tbl_b
where tbl_a.state = tbl_b.state
group by state
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.