简体   繁体   English

Big Query 是否支持自定义排序?

[英]Does Big Query support custom sorting?

I am trying to sort data by applying case when statement in the order by clause but looks like Big Query doesn't support even though it worked fine in other SQL environments.我试图通过在 order by 子句中应用 case when 语句来对数据进行排序,但看起来 Big Query 不支持,即使它在其他 SQL 环境中运行良好。 Can somebody share your thoughts on this.有人可以分享您对此的看法。

select x 
from (
  select x ,
  case when x = 'a' then 'z' else x end as y
  from 
    (select 'a' as x),
    (select 'b' as x),
    (select 'c' as x),
    (select 'd' as x)
  )
order by y desc

I think the documentation is pretty clear: 我认为文档很清楚:

ORDER BY clause ORDER BY子句

... ORDER BY field1|alias1 [DESC|ASC], field2|alias2 [DESC|ASC] ... ... ORDER BY field1 | alias1 [DESC | ASC],field2 | alias2 [DESC | ASC] ...

The ORDER BY clause sorts the results of a query in ascending or descending order of one or more fields. ORDER BY子句按一个或多个字段的升序或降序对查询结果进行排序。 Use DESC (descending) or ASC (ascending) to specify the sort direction. 使用DESC(降序)或ASC(升序)指定排序方向。 ASC is the default. ASC是默认值。

You can sort by field names or by aliases from the SELECT clause. 您可以按字段名称或SELECT子句中的别名进行排序。 To sort by multiple fields or aliases, enter them as a comma-separated list. 要按多个字段或别名排序,请将它们输入为逗号分隔列表。 The results are sorted on the fields in the order in which they are listed. 结果按字段顺序排列。

So, BigQuery doesn't allow expressions in the ORDER BY . 因此,BigQuery不允许在ORDER BY使用表达式。 However, you can include the expression in the SELECT and then refer to it by the alias. 但是,您可以在SELECT包含表达式,然后通过别名引用它。 So, BigQuery does support "custom sorting", but only by expressions in the SELECT . 因此,BigQuery确实支持“自定义排序”,但仅支持SELECT的表达式。

Interestingly, Hive has a similar limitation. 有趣的是,Hive有类似的限制。

Update (2021) - Bigquery now does support ORDER BY with expressions, eg更新 (2021) - Bigquery 现在支持 ORDER BY 表达式,例如


    SELECT event_type, COUNT(*) as event_count
    FROM events
    GROUP BY event
    ORDER BY (
        CASE WHEN event='generated' THEN 1
             WHEN event='sent' THEN 2
             WHEN event='paid' THEN 3
             ELSE 4
        END
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM