从单个表返回多个计数

时间:2014-02-18 16:27:01

标签: mysql sql select count case

我有以下格式的足球赛程表。

date date primary key
homescore int(4)
awayscore int(4)

数据以下列格式存储

DATE        |   HOMESCORE    |  AWAYSCORE
------------------------------------------
01-01-2014  |       1        |      0
08-01-2014  |       2        |      1
15-01-2014  |       1        |      1
22-01-2014  |       3        |      2
29-01-2014  |       0        |      0
06-02-2014  |       1        |      3  

等等......

我想运行一个查询来返回已赢,丢失和绘制的总数。

select count(*) as won from fixtures where homescore > awayscore;
select count(*) as lostfrom fixtures where homescore < awayscore;
select count(*) as drawnfrom fixtures where homescore = awayscore;

这个单一查询的结果看起来像......

Won      Lost      Drawn
3        1         2

请有人给我一些帮助。

3 个答案:

答案 0 :(得分:4)

SELECT SUM(homescore > awayscore) AS won,
   SUM(homescore < awayscore) AS lost,
   SUM(homescore = awayscore) AS tie
FROM ...

><=的布尔结果将通过mysql自动转换为整数01,然后可以总结一下。

答案 1 :(得分:2)

SQL Fiddle

SELECT SUM(CASE WHEN homescore > awayscore THEN 1 ELSE 0 END) WonCount,
       SUM(CASE WHEN homescore < awayscore THEN 1 ELSE 0 END) LostCount,
       SUM(CASE WHEN homescore = awayscore THEN 1 ELSE 0 END) TieCount
FROM fixtures 

答案 2 :(得分:0)

我遇到了同样的问题,在这些答案的基础上,我把一个SQL小提琴放在一起,这样你就可以自己试试。

http://sqlfiddle.com/#!2/066ec2/1

这是父母&#34;的一个人为的例子。和#34;孩子&#34;,但它表明获得&#34; stats&#34;对于连接表。谢谢你回答Marc B!