简体   繁体   中英

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?

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.

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

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