我想在 bigquery 中将列别名动态更改为 current_date()

I want to change column alias dynamically as current_date() in bigquery

我的查询:-

select 指标, 如果(d1 为空,"insp_not_done",d1)作为 d1, 如果(d2 为空,"insp_not_done",d2)作为 d2, 如果(d3 为空,"insp_not_done",d3)作为 d3, 如果(d4 为空,"insp_not_done",d4)作为 d4, 如果(d5 为空,"insp_not_done",d5)作为 d5, 如果(d6 为空,"insp_not_done",d6)作为 d6, 来自

( select “检查”作为公制,来自 xyz 的 d1、d2、d3、d4、d5、d6 table)

在这里,我希望 d1 为 current_date "2022-02-03",d2 为 current_date()-1 和明智的别名一样,但无法使其动态化在 bigquery 中找到正确的方法。 在此先感谢您的帮助。

从查询得到的输出:- enter image description here

需要输出:- enter image description here

我希望每次运行查询时 d1 都是 current_date 作为别名,d2 是 current_date()-1.

您的期望有所取舍。首先,您不能在列标签中使用 -,只能使用 _。其次,您不能以数字开头列标签。最后,您不能 运行 函数作为列别名。

但是,有一个解决办法。

事实上,您必须编写脚本并使用正确的别名创建查询,然后执行查询。这是一个虚拟示例

declare query string;
set query= "select 1 as " || FORMAT_DATE("_%Y_%m_%d", CURRENT_DATE()) ;
execute immediate query;

结果是

我可以提议的比你想要的更接近

考虑以下方法

execute immediate ('''
select * except(row_id) from (
select metric, dN, current_date - N as col, row_id
from ( 
  select "inspection" as metric, d1, d2, d3, d4, d5, d6, to_json_string(t) as row_id 
  from your_table t
), unnest([
  if(d1 is null,"insp_not_done",d1), 
  if(d2 is null,"insp_not_done",d2), 
  if(d3 is null,"insp_not_done",d3), 
  if(d4 is null,"insp_not_done",d4), 
  if(d5 is null,"insp_not_done",d5), 
  if(d6 is null,"insp_not_done",d6)
]) dN with offset as N
)
pivot (min(Dn) for col in (''' ||
(select string_agg("'" || date || "'", ',' order by offset desc)
from unnest(generate_date_array(current_date - 5, current_date)) date with offset) || "))"
)

如果像下面的例子一样应用于虚拟数据

create temp table your_table as (
  select '1' d1, null d2, '3' d3, '4' d4, null d5, '6' d6 union all
  select '21' d1, '22' d2, null d3, '24' d4, '25' d5, '26' d6   
);        

输出是