简体   繁体   English

在 DATE 类型上透视 BigQuery 表

[英]PIVOTing BigQuery tables on DATE type

I'm trying to pivot a table with each row being a transaction with a date.我正在尝试 pivot 一个表,其中每一行都是一个带有日期的事务。 Eg例如

WITH Produce AS (
  SELECT 'Kale' as product, 51 as sales, DATE('2020-01-01') as dates UNION ALL
  SELECT 'Kale', 23, DATE('2020-01-02') UNION ALL
  SELECT 'Kale', 45, DATE('2020-01-03') UNION ALL
  SELECT 'Kale', 3,  DATE('2020-01-04') UNION ALL
  SELECT 'Apple', 70, DATE('2020-01-01') UNION ALL
  SELECT 'Apple', 85, DATE('2020-01-02') UNION ALL
  SELECT 'Apple', 77, DATE('2020-01-03') UNION ALL
  SELECT 'Apple', 1, DATE('2020-01-04')
)

My query is something like this.我的查询是这样的。

SELECT * FROM Produce
PIVOT(sum(sales) FOR dates IN (DATE('2020-01-01'), DATE('2020-01-02'), DATE('2020-01-03'), DATE('2020-01-04')))

However BigQuery returns the following error.但是 BigQuery 返回以下错误。

Generating an implicit alias for this PIVOT value is not supported; please provide an explicit alias at [14:41]

According to the docs , pivot columns with type of date should be able to generate alias implicitly, or is my understanding wrong?根据文档,具有日期类型的 pivot 列应该能够隐式生成别名,还是我的理解错误?

Use below instead改用下面

SELECT * FROM Produce
PIVOT(sum(sales) FOR dates IN ('2020-01-01','2020-01-02', '2020-01-03', '2020-01-04'))          

with output与 output

在此处输入图像描述

From Rules for pivot_column:来自pivot_column 的规则:

A pivot_column must be a constant. pivot_column 必须是常量。

DATE('2020-01-01') is an expression, not a constant. DATE('2020-01-01')是一个表达式,而不是一个常量。 So you need to use one of followings.所以你需要使用以下之一。

PIVOT(sum(sales) FOR dates IN (DATE '2020-01-01', ...) -- explicit DATE literal
-- or
PIVOT(sum(sales) FOR dates IN ('2020-01-01', ...) -- literal implicitly coerced to DATE type
-- or
PIVOT(sum(sales) FOR dates IN (DATE('2020-01-01') AS _2020_01_01, ...) -- alias


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

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