7

I am writing a horse racing web app and i have a stats page. What i am trying to do is show how many winners there are from each year.

Currently i have this:

SELECT `Horse Number`, Count(*) AS `Total Winners`
FROM `races`.`2009`
WHERE `Win $`>0 
GROUP BY `Horse Number`
ORDER BY Count(*) DESC;

It works like a charm and returns the following

Horse Number | Total Winners
1|48
2|49
3|39
4|31
5|26
6|31
7|21
8|25
9|31
10|16
11|16
12|20
13|9
14|8
15|6
16|3
17|3
18|2
19|2

I have now created a table for 2010 and i am wanting SQL to return something similar but i want it to search over 2009 and 2010 at the same time. I thought something like this might do the trick.

SELECT `Horse Number`, Count(*) AS `Total Winners`
FROM `races`.`2009`
WHERE `Win $`>0 
GROUP BY `Horse Number`
UNION
SELECT `Horse Number`, Count(*) AS `Total Winners`
FROM `races`.`2010`
WHERE `Win $`>0 
GROUP BY `Horse Number`
ORDER BY Count(*) DESC;

But it is just returning extra results at the bottom of the table so i now have 2 rows for each horse like this

Horse Number | Total Winners
1|48
2|49
3|39
4|31
5|26
6|31
7|21
8|25
9|31
10|16
11|16
12|20
13|9
14|8
15|6
16|3
17|3
18|2
19|2
1|0
2|0
3|0
4|0
5|0
6|0
7|0
8|0
9|0
10|0
11|0
12|0
13|0
14|0
15|0
16|0
17|0
18|0
19|0

Is anyone able to assist me please

Thanks

2
  • 7
    Storing your result in a different table for each year is not the SQL way. You should use a single table with a year column with an index on that column. This will make things a lot easier for you. Commented Jan 1, 2010 at 8:36
  • This is why per-period tables are not for the uninitiated. Commented Jan 1, 2010 at 8:37

1 Answer 1

10

First off, I would suggest having ONE table with an extra column for a year.

Second, with the current table structure, you can do

SELECT `Horse Number`, Count(*) AS `Total Winners`
FROM (
  SELECT * FROM `races`.`2009`
  UNION ALL
  SELECT * FROM `races`.`2010`
) all_races
WHERE `Win $`>0 
GROUP BY `Horse Number`
ORDER BY Count(*) DESC;
Sign up to request clarification or add additional context in comments.

4 Comments

You want UNION ALL there, not UNION.
Yep, was somehow assuming rows are unique across 2 tables which could be false. Fixed
Can you use square brackets instead of apostrophes for your columns please? It's way more preferred, as 'Horse Number' could easily be interpreted as a string in your outer query.
@Rob - I never heard of square brackets used that way, is that standard transact SQL fare? BTW, I was merely cut/n/pasting OP's query here, theres lots of differences to my own style :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.