选择指向最高价值的价值

时间:2019-10-25 12:07:40

标签: google-bigquery

我有一张这样的桌子:

enter image description here

我想将表格转换为此:

enter image description here

要获得表2,我将第1列中的值分组,然后选择第2列中持续时间最高的值。有人可以帮我语法吗?

2 个答案:

答案 0 :(得分:1)

一种解决方案是在数据中添加一个ROW_NUMBER(),该数据在“ Duration”字段中排序,然后对该行号进行过滤,因此您只从分区中选择最高的值。

以下是一个基于您的屏幕截图的虚拟数据示例:

WITH table AS (
  SELECT 1 column1, 100 column2, 3 Duration UNION ALL
  SELECT 1, 101, 7 UNION ALL
  SELECT 1, 102, 5 UNION ALL
  SELECT 2, 108, 5 UNION ALL
  SELECT 2, 109, 9 
)

    SELECT * EXCEPT (rn) FROM(
    SELECT column1, 
    column2, 
    Duration, 
    ROW_NUMBER() OVER(PARTITION BY column1 ORDER BY Duration DESC) AS rn 
    FROM table
    )
    WHERE rn = 1

哪个返回结果:

enter image description here

答案 1 :(得分:0)

以下是Bigquery标准SQL

this.router.navigate(['/yoururl'], { queryParams: { type: someVariable, entity: someVariable } });

您可以使用问题中的示例数据来测试,玩游戏,如下例所示

#standardSQL
SELECT AS VALUE ARRAY_AGG(t ORDER BY duration DESC LIMIT 1)[OFFSET(0)]
FROM `project.dataset.table` t
GROUP BY column1   

有结果

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'A' column1, 100 column2, 3 duration UNION ALL
  SELECT 'A', 101, 7 UNION ALL
  SELECT 'A', 102, 5 UNION ALL
  SELECT 'B', 108, 5 UNION ALL
  SELECT 'B', 109, 9 
)
SELECT AS VALUE ARRAY_AGG(t ORDER BY duration DESC LIMIT 1)[OFFSET(0)]
FROM `project.dataset.table` t
GROUP BY column1