mysql程序设计排球比赛,MySQL排球榜

I have a database table full of game by game results and want to know if I can calculate the following:

GP (games played)

Wins

Loses

Points (2 points for each win, 1 point for each lose)

Here is my table structure:

CREATE TABLE `results` (

`id` int(10) unsigned NOT NULL auto_increment,

`home_team_id` int(10) unsigned NOT NULL,

`home_score` int(3) unsigned NOT NULL,

`visit_team_id` int(10) unsigned NOT NULL,

`visit_score` int(3) unsigned NOT NULL,

`tcl_id` int(3) unsigned NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

And a few testing results:

INSERT INTO `results` VALUES(1, 1, 21, 2, 25, 68);

INSERT INTO `results` VALUES(2, 3, 21, 4, 17, 68);

INSERT INTO `results` VALUES(3, 1, 25, 3, 9, 68);

INSERT INTO `results` VALUES(4, 2, 7, 4, 22, 68);

INSERT INTO `results` VALUES(5, 1, 19, 4, 20, 68);

INSERT INTO `results` VALUES(6, 2, 24, 3, 26, 68);

Here is what a final table would look something like this (results are not completely accurate):

+-------------------+----+------+-------+--------+

| Team Name | GP | Wins | Loses | Points |

+-------------------+----+------+-------+--------+

| Spikers | 4 | 4 | 0 | 8 |

| Leapers | 4 | 2 | 2 | 6 |

| Ground Control | 4 | 1 | 3 | 5 |

| Touch Guys | 4 | 0 | 4 | 4 |

+-------------------+----+------+-------+--------+

Need to add WHERE clause fortcl_id like so:

WHERE results.tcl_id = 68

Thank you in advance.

解决方案

This should do what you want:

SELECT

team_id,

COUNT(*) AS GP,

SUM(is_win) AS Wins,

SUM(NOT is_win) AS Losses,

2 * SUM(is_win) + SUM(NOT is_win) AS Points

FROM

(

SELECT

home_team_id AS team_id,

home_score > visit_score AS is_win

FROM results

WHERE tcl_id = 68

UNION ALL

SELECT

visit_team_id AS team_id,

home_score < visit_score AS is_win

FROM results

WHERE tcl_id = 68

) T1

GROUP BY team_id

ORDER BY Points DESC

Output for your example data:

4, 3, 2, 1, 5

3, 3, 2, 1, 5

1, 3, 1, 2, 4

2, 3, 1, 2, 4

Notes:

Your example data doesn't seem to match with your expected output - your test data only has 6 games played, but your expected output has 8 games. This is why my output is different from yours.

You haven't provided the table for getting the team names from the team ids. Just join with your table with the team names to get the result in the format you want.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值