更新数据集以添加计算字段

时间:2013-04-25 10:16:49

标签: sql tsql

我有一个数据集见下文:

SELECT jockey.jockey_skey
, raceresults.place 
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 
ORDER  BY jockey.jockey_skey 

这为我提供了:

Jockey_Skey    Place
1              01
1              04
2              03
2              04
3              02
3              02

我想做的是计算骑师跑了多少场比赛以及他们来的名单。

所以赛马会1,比赛2次,第1次到第4次,所以第4次,但对于我的生活,我不记得该怎么做。

1 个答案:

答案 0 :(得分:1)

你可以使用这样的东西来获得一行中每个骑师的结果:

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 

<强> Simplified Example on 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值代表总数

<强> Simplified Example on SQL Fiddle