SQL:检测两个表之间的总和差异?

时间:2011-02-23 20:47:01

标签: sql sum

看起来很简单:我有两票,我想看看哪些州有不同的票数。单独来说,这很容易:

select state, sum(votes) from votes_a group by state;

select state, sum(votes) from votes_b group by state;

如何针对具有不同结果的状态查询state, votes_a, votes_b之类的内容?

2 个答案:

答案 0 :(得分:2)

尝试加入:

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

请注意,这将错过其中一个表中获得零票的州。要解决此问题,您可以使用FULL OUTER JOIN(假设您的数据库支持此功能)并检查NULL。

答案 1 :(得分:0)

试试这个......

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