谷歌大查询行之间的差异

时间:2017-10-11 18:34:04

标签: sql google-bigquery lag

我目前正在尝试计算Google大查询中各行之间的差异。我实际上有一个有效的查询。

 SELECT
    id, record_time, level, lag,
    (level - lag) as diff
 FROM (
   SELECT
      id, record_time, level, 
      LAG(level) OVER (ORDER BY id, record_time) as lag
   FROM (
      SELECT
        *
      FROM
        TABLE_QUERY(MY_TABLES))
   ORDER BY
      1, 2 ASC
    )
 GROUP BY 1, 2, 3, 4
 ORDER BY 1, 2 ASC

但我正在使用大数据,有时我有内存限制警告,不允许我执行查询。所以,我想了解为什么我不能像bellow那样进行优化查询。我认为这样可以在没有内存限制警告的情况下使用更多记录。

   SELECT
      id, record_time, level,
      level - LAG(level, 1) OVER (ORDER BY id, record_time) as diff
   FROM (
      SELECT
        *
      FROM
        TABLE_QUERY(MY_TABLES))
   ORDER BY
      1, 2 ASC

执行查询时的这种函数level - LAG(level, 1) OVER (ORDER BY id, record_time) as diff,将返回错误

  

分析表达式中缺少函数

关于Big Query。

我还尝试将( )放入此函数中,但它也不起作用。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

对我来说很好。也许你忘了enable standard SQL?这是一个例子:

WITH Input AS (
  SELECT 1 AS id, TIMESTAMP '2017-10-17 00:00:00' AS record_time, 2 AS level UNION ALL
  SELECT 2, TIMESTAMP '2017-10-16 00:00:00', 3 UNION ALL
  SELECT 1, TIMESTAMP '2017-10-16 00:00:00', 4
)
SELECT
 id, record_time, level, lag,
 (level - lag) as diff
FROM (
  SELECT
    id, record_time, level, 
    LAG(level) OVER (ORDER BY id, record_time) as lag
  FROM Input
)
GROUP BY 1, 2, 3, 4
ORDER BY 1, 2 ASC;