【问题标题】:BigQuery - Select the minimum value of a column dependant upon the value in another columnBigQuery - 根据另一列中的值选择列的最小值
【发布时间】:2023-03-23 01:10:02
【问题描述】:

假设我有一张这样的桌子

userId  eventType   timing
647     'jump'      32.7
123     'skip'      13.1
647     'skip'      24.4
433     'jump'      12.7 
433     'skip'      53.6 
647     'jump'      2.4 
647     'jump'      64.4 
123     'skip'      14.0
433     'jump'      4.3 
123     'jump'      18.6

我想输出一个表,其中每个 userId 有一行,列为 userId,该 userId 的 eventType 为“skip”的最短时间以及同一 userId 的 eventType 为“jump”的最短时间。像这样。

userID  first_skip  first_jump  
647     24.4        2.4
123     13.1        18.6
433     53.6        4.3

我意识到我可以通过连接来做到这一点。

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 647 userId, 'jump' eventType, 32.7 timing UNION ALL
  SELECT 123, 'skip', 13.1 UNION ALL
  SELECT 647, 'skip', 24.4 UNION ALL
  SELECT 433, 'jump', 12.7 UNION ALL
  SELECT 433, 'skip', 53.6 UNION ALL
  SELECT 647, 'jump', 2.4 UNION ALL
  SELECT 647, 'jump', 64.4 UNION ALL
  SELECT 123, 'skip', 14.0 UNION ALL
  SELECT 433, 'jump', 4.3 UNION ALL
  SELECT 123, 'jump', 18.6
)

SELECT 
  raw.userID, 
  MIN(skips.timing) AS first_skip,
  MIN(jumps.timing) AS first_jump,
FROM `project.dataset.table` AS raw
LEFT JOIN `project.dataset.table` AS skips ON raw.userId = skips.userId
LEFT JOIN `project.dataset.table` AS jumps ON raw.userId = jumps.userId
WHERE skips.eventType = 'skip' AND jumps.eventType = 'jump'
GROUP BY userId

但是,我的实际数据非常大,并且还有一些 eventType 类别,这意味着查询需要永远处理。我想知道是否有一种更好、更有效的方法来做到这一点,它不使用连接。也许使用windowpartition

【问题讨论】:

    标签: sql google-bigquery pivot min


    【解决方案1】:

    使用条件聚合:

    select userid,
        min(case when eventtype = 'skip' then timing end) first_skip,
        min(case when eventtype = 'jump' then timing end) first_jump
    from mytable
    group by userid
    

    【讨论】:

      【解决方案2】:

      您可以使用条件聚合:

      select user_id, 
             min(case when eventtype = 'skip' then timing end) as skip,
             min(case when eventtype = 'jump' then timing end) as jump
      from t
      group by user_id;
      

      【讨论】:

        猜你喜欢
        • 2014-10-05
        • 2021-05-25
        • 2018-08-25
        • 1970-01-01
        • 2012-05-29
        • 2022-09-29
        • 1970-01-01
        • 2018-01-02
        • 1970-01-01
        相关资源
        最近更新 更多