sql - 如何对每个唯一版本: For each unique id,,抓取最好的分数整理成表格

标签 sql google-bigquery

只是想先说明一下,虽然我确实有基本的了解,但我对一般使用 Bigquery 表和 sql 语句还是相当陌生。

我正在尝试从一个查询中创建一个新 View ,该查询获取每个员工每个版本的所有最佳测试分数:

select emp_id,version,max(score) as score from `project.dataset.table` where type = 'assessment_test' group by version,emp_id order by emp_id

我想获取该查询的结果,并创建一个由员工 ID 组成的新表,其中每个版本的列都有一列,该行 emp_id。我知道我可以通过包含“where version = a”、“where version = b”等来手动为每个版本创建一个表......然后在最后加入所有表,但这似乎不是就像最优雅的解决方案一样,总共有大约 20 个不同的版本。

有没有办法以编程方式为每个唯一版本创建一个列,或者至少将我的初始查询用作子查询并仅引用它,如下所示:

with a as (
  select id,version,max(score) as score 
  from `project.dataset.table` 
  where type = 'assessment_test' and version is not null and score is not null and id is not null 
  group by version,id 
  order by id),

version_a as (select score from a where version = 'version_a')
version_b as (select score from a where version = 'version_b')
version_c as (select score from a where version = 'version_c')

select 
  a.id as id,
  version_a.score as version_a,
  version_b.score as version_b,
  version_c.score as version_c
from 
a,
version_a, 
version_b,
version_c

Example Picture: left table is example data, right table is expected output

示例数据:

<表类="s-表"> <头> id 版本 得分 <正文> 1 一个 88 1 b 93 1 c 92 2 一个 89 2 b 99 2 c 78 3 一个 95 3 b 83 3 c 89 4 一个 90 4 b 90 4 c 86 5 一个 82 5 b 78 5 c 98 1 一个 79 1 b 97 1 c 77 2 一个 100 2 b 96 2 c 85 3 一个 83 3 b 87 3 c 96 4 一个 84 4 b 80 4 c 77 5 一个 95 5 b 77

预期输出:

<表类="s-表"> <头> id 分数 b 得分 c 得分 <正文> 1 88 97 92 2 100 99 85 3 95 87 96 4 90 90 86 5 95 78 98

提前致谢,如有任何需要澄清的问题,请随时提出

最佳答案

使用下面的方法

select * from your_table
pivot (max(score) score for version in ('a', 'b', 'c'))      

如果应用于您问题中的示例数据 - 输出为

enter image description here

如果事先不知道版本 - 使用下面

execute immediate (select '''
select * from your_table
pivot (max(score) score for version in (''' || string_agg(distinct "'" || version || "'") || "))"
from your_table
)

关于sql - 如何对每个唯一版本: For each unique id,,抓取最好的分数整理成表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72877218/

相关文章:

SQL 根据另一个表删除行

google-bigquery - 字符串到日期时间的转换 Bigquery

google-bigquery - 如何以编程方式访问“保存的查询”?

arrays - Bigquery - 如何将两个数组压缩为一个?

google-bigquery - 通过 Apache Beam 写入动态 BigQuery 表

sql - 您如何计算 BigQuery 中列的 bool 聚合?

mysql - 如果我选择两个没有 WHERE 子句的表会怎样?

c# - 在SQL中从一行中选择多行

mysql - 比较值,对它们进行排序并确定哪个更有利

sql - 使用 CTE 的优点/缺点是什么?