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

Does Big Query support custom sorting?

我正在尝试通过在 order by 子句中应用 case when 语句来对数据进行排序,但看起来 Big Query 不支持,即使它在其他 SQL 环境中运行良好。有人可以分享您对此的看法吗?

我认为文档很清楚:

ORDER BY clause

... 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. Use DESC (descending) or ASC (ascending) to specify the sort direction. ASC is the default.

You can sort by field names or by aliases from the SELECT clause. 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.

因此,BigQuery 不允许 ORDER BY 中的表达式。但是,您可以在 SELECT 中包含表达式,然后通过别名引用它。因此,BigQuery 确实支持 "custom sorting",但仅支持 SELECT.

中的表达式

有趣的是,Hive 也有类似的限制。

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

更新 (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
    )