输出2列,平均年份为t年,年份为t + 1

时间:2018-03-28 12:50:38

标签: sql sql-server

我有一个看起来像这样的表:

| playerid  | season  | Stat    |
|-----------|---------|---------|
| 1         | 2014    | 2.3     |
| 1         | 2015    | 1.4     |
| 1         | 2016    | 3.5     |
| 2         | 2011    | 1.5     |
| 2         | 2012    | 5.5     |
| 3         | 2010    | 6.7     |
| 3         | 2011    | 2.6     |

我想要一张包含2列平均值的表格' STAT'对于第1列中的第t年和第2列中的第t + 1年。

IE-Column 1的平均值为' Stat'为:

 playerid=1 & season=2014, 
 playerid=1 & season=2015, 
 playerid=2 & season=2011, 
 playerid=3 & season=2010.

第2列的平均值为' Stat'为:

 playerid=1 & season=2015,
 playerid=1 & season=2016,
 playerid=2 & season=2012,
 playerid=3 & season=2011.

2 个答案:

答案 0 :(得分:0)

明年你可以用left join

查找
select  cur.playerid
,       cur.season
,       cur.stat as stat_this_season
,       next.stat as stat_next_season
from    YourTable cur
left join
        YourTable next
on      cur.playerid = next.playerid
        and cur.year = next.year - 1

要过滤掉下一季没有的季节,请将left join更改为inner join(您可以将其缩写为join。)

答案 1 :(得分:0)

您可以使用分析函数ROW_NUMBER()按年份为每个玩家排序。然后,您可以通过排除第一个记录(对于第1列)和最后一个记录(对于第2列)来获取所请求的平均值。如果只有一个季节,Stat将仅包含在第1列中。

SELECT t.playerid,
       AVG(CASE WHEN t.ord1 != 1 OR
                     (t.ord1 = 1 AND t.ord2 = 1) THEN Stat END) AS Column_1,
       AVG(CASE WHEN t.ord2 != 1 THEN Stat END) AS Column_2
  FROM (SELECT s.*,
               ROW_NUMBER() OVER (PARTITION BY playerid ORDER BY season DESC) AS ord1,
               ROW_NUMBER() OVER (PARTITION BY playerid ORDER BY season ASC) AS ord2
          FROM table_1 s) t
 GROUP BY playerid
 ORDER BY playerid

如果您从之前的查询中移除GROUP BY,您将只获得一行,其中包含所有玩家的平均值:

SELECT AVG(CASE WHEN t.ord1 != 1 OR
                     (t.ord1 = 1 AND t.ord2 = 1) THEN Stat END) AS Column_1,
       AVG(CASE WHEN t.ord2 != 1 THEN Stat END) AS Column_2
  FROM (SELECT s.*,
               ROW_NUMBER() OVER (PARTITION BY playerid ORDER BY season DESC) AS ord1,
               ROW_NUMBER() OVER (PARTITION BY playerid ORDER BY season ASC) AS ord2
          FROM table_1 s) t