如何使用行号对这个BigQuery查询进行分页?

时间:2019-03-06 16:25:29

标签: sql google-bigquery

如何更新此BigQuery查询以允许附加的分页条款?

SELECT test.id, test.city, ROW_NUMBER() OVER () rownumber FROM prod.test LEFT OUTER JOIN prod.locations AS location ON (test.city = location.id)
WHERE active = true 
AND rownumber BETWEEN 10000 AND 30000 

产生的错误是:

  

无法识别的名称:行号

3 个答案:

答案 0 :(得分:1)

在此示例中,使用子查询:

SELECT t.*
FROM (SELECT test.id, test.city, ROW_NUMBER() OVER () rownumber
      FROM prod.test LEFT OUTER JOIN
           prod.locations location
           ON test.city = location.id
      WHERE active = true
     ) t 
WHERE rownumber BETWEEN 10000 AND 30000 ;

但是,您可能应该使用LIMITOFFSET

答案 1 :(得分:1)

您还可以使用CTE

with cte as
(
 SELECT test.id, test.city, ROW_NUMBER() OVER () rownumber 
 FROM prod.test LEFT OUTER JOIN prod.locations AS location ON (test.city = location.id)
WHERE active = true
 ) select * from cte where rownumber BETWEEN 10000 AND 30000 

行号是直接在where子句中不支持的内联别名

答案 2 :(得分:1)

如果bigquery支持,则可以使用此标准sql子句,

SELECT 
       test.id
      ,test.city
FROM prod.test as test 
LEFT OUTER JOIN prod.locations AS location ON (test.city = location.id)
    WHERE active = true
order by test.id
offset 10000 rows fetch next 20000 rows only