赛马(SQL解惑读书笔记二)

有一个赛马表如下
create table RacingResults (
	trace_id char(3) not null,
	race_date date not null,
	race_nbr int not null,
	win_name char(30) not null,
	place_name char(30) not null,
	show_name char(30) not null,
	primary key (trace_id, race_date, race_nbr)
) type=InnoDB default charset="UTF8";


trace_id列是举行比赛的赛道的名称,race_date是举行比赛的日期,race_nbr是每次比赛的编号,
另外3列是在比赛获得第一、第二和第三名的马的名字.
win表示马是第一名.
place表示马是第一或第二名.
show表示马是第一、第二或第三名.

要求:取得每匹马获奖的次数.数据如下:

insert into RacingResults values
("001", "2008-12-25", 1, "horce1", "horce2", "horce3"),
("002", "2008-12-25", 1, "horce2", "horce3", "horce4"),
("003", "2008-12-25", 1, "horce3", "horce4", "horce5"),
("004", "2008-12-25", 1, "horce4", "horce5", "horce6"),
("005", "2008-12-25", 1, "horce5", "horce6", "horce7"),
("006", "2008-12-25", 1, "horce6", "horce7", "horce8"),
("007", "2008-12-25", 1, "horce7", "horce8", "horce9");


思路:取得所有的马,去除重复的,再与赛马表关联,计算个数.

答案如下:
select n.win_name, count(*) from RacingResults r, 
(select win_name from RacingResults
union
select place_name from RacingResults
union
select show_name from RacingResults)
as n
where r.win_name = n.win_name 
or 
r.place_name = n.win_name
or
r.show_name = n.win_name
group by (n.win_name);

你可能感兴趣的:(sql,读书)