将列值作为日期部分参数传递

时间:2019-07-17 09:24:11

标签: google-bigquery

我正在尝试生成一个工作日的字符串数组,并使用它来查找一个月中每天出现多少次

我在BigQuery上使用标准sql

我的查询看起来像

with weeks as (select array['SUNDAY','MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY'] as wk)
select DATE_DIFF('2019-01-31','2019-01-01',WEEK(wk)) AS week_weekday_diff 
from weeks, unnest(wk) as wk

但是,查询失败,错误为A valid date part argument for WEEK is required, but found wk。 wk是具有星期几的列值,WEEK是需要文字DAYOFWEEK的函数。有没有办法将列值作为参数传递

2 个答案:

答案 0 :(得分:1)

尝试查询时,我发现返回的错误是:

select DATE_DIFF('2019-01-31','2019-01-01',WEEK('WEDNESDAY')) AS week_weekday_diff; 

因为函数WEEK()期望如下所示:

select DATE_DIFF('2019-01-31','2019-01-01',WEEK(`WEDNESDAY`)) AS week_weekday_diff; 

OR

select DATE_DIFF('2019-01-31','2019-01-01',WEEK('WEDNESDAY')) AS week_weekday_diff; 

我认为WEEK()仅接受公开的here格式的工作日,因此任何字符串都不应该有效。

答案 1 :(得分:1)

以下是用于BigQuery标准SQL

  

错误“必须提供WEEK的有效日期部分参数,但发现是周”

WEEK(<WEEKDAY>): Valid values for WEEKDAY are literal SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.   
  

...有没有办法将列值作为参数传递?

如果您愿意-您可以在https://issuetracker.google.com/issues/new?component=187149&template=0上提交功能请求

  

查找一个月中每天出现几次

要获得预期的结果并克服“问题”,您可以从相反的角度进行任务-只需提取工作日的职位,然后执行所需的统计信息即可,如下面的示例

#standardSQL
WITH weekdays AS (SELECT ['SUNDAY','MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY'] AS wk)
SELECT wk[ORDINAL(pos)] weekday, COUNT(1) cnt
FROM weekdays, 
  UNNEST(GENERATE_DATE_ARRAY('2019-01-01','2019-01-31')) day, 
  UNNEST([EXTRACT(DAYOFWEEK FROM day)]) pos
GROUP BY pos, weekday
ORDER BY pos

有结果

Row weekday     cnt  
1   SUNDAY      4    
2   MONDAY      4    
3   TUESDAY     5    
4   WEDNESDAY   5    
5   THURSDAY    5    
6   FRIDAY      4    
7   SATURDAY    4