赛马(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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值