SQL计数(*)在多个表上 [英] SQL Count(*) on multiple tables
问题描述
我在写一个赛马网络应用程序,我有一个统计页面。
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.
目前我有这个:
SELECT `Horse Number`, Count(*) AS `Total Winners`
FROM `races`.`2009`
WHERE `Win $`>0
GROUP BY `Horse Number`
ORDER BY Count(*) DESC;
它的作用类似于charm,并返回以下
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
我现在已经为2010创建了一个表,我希望SQL返回类似的东西,但我想要在2009和2010年同时搜索。
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;
但它只是在表的底部返回额外的结果,所以我现在有2行为每个马像这样
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
感谢
推荐答案
其次,使用当前的表结构,您可以执行
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;
这篇关于SQL计数(*)在多个表上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!