您可以使用这样的方法来获取一行中每个骑师的结果:
SELECT jockey.jockey_skey,
TotalRaces = COUNT(*),
[1sts] = COUNT(CASE WHEN raceresults.place = '01' THEN 1 END),
[2nds] = COUNT(CASE WHEN raceresults.place = '02' THEN 1 END),
[3rds] = COUNT(CASE WHEN raceresults.place = '03' THEN 1 END),
[4ths] = COUNT(CASE WHEN raceresults.place = '04' THEN 1 END),
[5ths] = COUNT(CASE WHEN raceresults.place = '05' THEN 1 END),
[6ths] = COUNT(CASE WHEN raceresults.place = '06' THEN 1 END),
[7ths] = COUNT(CASE WHEN raceresults.place = '07' THEN 1 END),
[8ths] = COUNT(CASE WHEN raceresults.place = '08' THEN 1 END),
-- etc
[NonRunner] = COUNT(CASE WHEN raceresults.place = 'NR' THEN 1 END),
[Fell] = COUNT(CASE WHEN raceresults.place = 'F' THEN 1 END),
[PulledUp] = COUNT(CASE WHEN raceresults.place = 'PU' THEN 1 END),
[Unseated] = COUNT(CASE WHEN raceresults.place = 'U' THEN 1 END),
[Refused] = COUNT(CASE WHEN raceresults.place = 'R' THEN 1 END),
[BroughtDown] = COUNT(CASE WHEN raceresults.place = 'B' THEN 1 END)
FROM jockey
INNER JOIN runnersandriders
ON jockey.jockey_skey = runnersandriders.jockey_skey
INNER JOIN horse
ON runnersandriders.horse_skey = horse.horse_skey
INNER JOIN raceresults
ON horse.horse_skey = raceresults.horse_skey
GROUP BY jockey.jockey_skey
ORDER BY jockey.jockey_skey
SQL Fiddle 的简化示例
或者,您可以使用WITH ROLLUP
获取额外的总计行:
SELECT jockey.jockey_skey,
raceresults.place,
[CountOfResult] = COUNT(*)
FROM jockey
INNER JOIN runnersandriders
ON jockey.jockey_skey = runnersandriders.jockey_skey
INNER JOIN horse
ON runnersandriders.horse_skey = horse.horse_skey
INNER JOIN raceresults
ON horse.horse_skey = raceresults.horse_skey
GROUP BY jockey.jockey_skey, raceresults.place
WITH ROLLUP
ORDER BY jockey.jockey_skey, raceresults.place;
其中NULL
值代表总计
SQL Fiddle 的简化示例