469,898 Members | 1,626 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,898 developers. It's quick & easy.

Subtracting grouped counts

I have two COUNT-queries that I which to subtract. The first query is like:
SELECT winner, COUNT(winner)
FROM my_table
GROUP BY winner

The second is like:

SELECT contributor, COUNT(contributor)
FROM my_table
GROUP BY contributor

The first query returns two columns with values (John, Jane);(2,3) and the second returns (John,Jane,Jack);(1,1,3). Now I want to subtract the first and the second so that the result is (John,Jane,Jack);(1,2,-3). How can this be accomplished? Any help much appreciated.
Feb 10 '08 #1
2 4603
1,134 Expert 1GB
Try this

Expand|Select|Wrap|Line Numbers
  1. SELECT a.contributor,isnull(b.cnt,0) - a.cnt as Cnt
  2. FROM
  3. (SELECT contributor, COUNT(contributor)  as Cnt
  4. FROM my_table
  5. GROUP BY contributor) a
  6. left join
  7. (SELECT winner, COUNT(winner) as Cnt
  8. FROM my_table
  9. GROUP BY winner)b on a.contributor=b.winner
Feb 11 '08 #2
Great! Thanks a lot.
Feb 11 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by Steven Bethard | last post: by
reply views Thread by Andres | last post: by
8 posts views Thread by simpleman | last post: by
2 posts views Thread by Chris via AccessMonster.com | last post: by
3 posts views Thread by Martin Joergensen | last post: by
1 post views Thread by Waqarahmed | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.