如何在 BigQuery 中使用 PIVOT 使用参数而不是实际日期?

问题描述 投票:0回答:1

我在我的服务器中使用以下查询,我需要使列成为动态的而不是字符串。 我尝试使用:

    UNNEST(GENERATE_DATE_ARRAY('2024-03-12', '2024-03-25', INTERVAL 1 DAY))

但我收到错误:

    Syntax error: Unexpected keyword UNNEST

有什么替代方案吗?

       (
        
        SELECT * FROM
          ( SELECT 
                DATE(Date) AS Date,
                Region,
                Revnue
                
            FROM
          `analy-417.AM.Overview` where 2 is not null
        )
          PIVOT(sum(Revnue) FOR Date IN ('2024-03-25','2024-03-24','2024-03-23','2024-03-22','2024-03-21','2024-03-20','2024-03-19','2024-03-18','2024-03-17','2024-03-16','2024-03-15','2024-03-14','2024-03-13','2024-03-12'))
    
      )
sql google-bigquery pivot-table
1个回答
0
投票

这是使用左连接取消嵌套的替代方法,而不必写出所有日期。制作了一个模拟表来了解 CTE/with 函数的结果。

WITH
  mock_data AS (
  SELECT
    '2024-03-12' AS date,
    'NA' AS region,
    999999 AS revenue
  UNION ALL
  SELECT
    '2024-03-12' AS date,
    'NA' AS region,
    200000 AS revenue
  UNION ALL
  SELECT
    '2024-03-13' AS date,
    'NA' AS region,
    0 AS revenue)
SELECT
  date,
  region,
  SUM(revenue) AS revenue_sum
FROM
  mock_data
WHERE
  CAST(date AS date) IN (
  SELECT
    date
  FROM (
    SELECT
      date
    FROM (
      SELECT
        NULL)
    LEFT JOIN
      UNNEST (GENERATE_DATE_ARRAY('2024-03-12', '2024-03-25', INTERVAL 1 DAY)) AS date))
GROUP BY
  date,
  region
© www.soinside.com 2019 - 2024. All rights reserved.