BigQuery或SQL中的Delta方法?

时间:2017-04-28 16:04:16

标签: mysql sql google-app-engine google-bigquery

所以我试图建立一个delta曲线,看看MLB球员的表现如何随着年龄的增长而变化。

  

“delta方法”着眼于所有在背靠背比赛中出场的球员。许多球员显然有几个背靠背的年份“对联”。对于每个玩家来说,它取决于他们在第一年和第二年的表现率之间的差异,并把这个差异放到一个“桶”中,这是由玩家在这两年中的年龄来定义的。

所以,让我们说一名球员在他25岁的时候发布了平均击球率为.300,然后在他26岁的时候发布了平均.310。所以我们采取了+10的差异,我们把25/26岁的“桶” ”。

所以我有一个像这样构建的表:

ID   Name      Age  Average
123  Joe Smith  25  .300
123  Joe Smith  26  .310
123  Joe Smith  27  .312
123  Joe Smith  28  .315

所以我正在寻找的输出基本上就是我正在创建一个新行,它可以识别所有我们看到玩家背靠背赛季平均差异的情况(所以如果有人有一个年龄的话) 25个赛季,但不是26个赛季,他们不会被包括在内)。我确信这涉及某种CASE声明,但我对这一切都有点生疏。如果您不了解BigQuery,请随意回复,如果这是SQL。

2 个答案:

答案 0 :(得分:1)

在下面尝试BigQuery Standard SQL

  
#standardSQL
SELECT ID, Name, Age, Average, bucket, ROUND(diff, 3) AS diff
FROM (
  SELECT *,
    CONCAT(CAST(Age AS STRING), '/', CAST(Age + 1 AS STRING)) AS bucket, 
    MAX(Average) OVER(nextYear) - Average AS diff
  FROM yourTable
  WINDOW nextYear AS (PARTITION BY ID ORDER BY Age RANGE BETWEEN 1 FOLLOWING AND 1 FOLLOWING)
)
WHERE IFNULL(diff, 0) <> 0 
-- ORDER BY ID, Age  

您可以使用问题中的虚拟数据进行测试/播放

#standardSQL
WITH yourTable AS (
  SELECT 123 AS ID, 'Joe Smith' AS Name, 25 AS Age, .300 AS Average UNION ALL
  SELECT 123, 'Joe Smith', 26, .310 UNION ALL
  SELECT 123, 'Joe Smith', 27, .312 UNION ALL
  SELECT 123, 'Joe Smith', 28, .315 
)
SELECT ID, Name, Age, Average, bucket, ROUND(diff, 3) AS diff
FROM (
  SELECT *,
    CONCAT(CAST(Age AS STRING), '/', CAST(Age + 1 AS STRING)) AS bucket, 
    MAX(Average) OVER(nextYear) - Average AS diff
  FROM yourTable
  WINDOW nextYear AS (PARTITION BY ID ORDER BY Age RANGE BETWEEN 1 FOLLOWING AND 1 FOLLOWING)
)
WHERE IFNULL(diff, 0) <> 0 
ORDER BY ID, Age

答案 1 :(得分:0)

在sql中,我会在id上进行自我加入,年龄+ 1 =年龄并计算差异:

select t1.id, t1.name, t1.age, t2.age, t1.average, t2.average, t2.average-t1.average as diff, concat(t1.age,'/',t2.age) as bucket
from yourtable t1
inner join yourtable t2
on t1.id=t2.id and t1.age+1=t2.age

内部联接将确保如果下一年没有完成的季节,那么记录不会包含在结果集中。