0

输入: 在 bigquery 中有一个表格,格式如下

Store   Date        WeekNumber
11      2019-11-14  201953
11      2019-11-12  201953
11      2019-11-17  201953
11      2019-11-15  201953
11      2019-11-11  201953
11      2019-11-13  201953
11      2019-11-16  201953
11      2019-11-19  201954
11      2019-11-21  201954
11      2019-11-22  201954

场景:从上面的示例表中,必须按周数分组并获取示例输出中提到的周的开始日期。

样本输出:

Store   StartDate       WeekNumber
11      2019-11-11      201953
11      2019-11-19      201954

查询片段:

SELECT
Store,
#StartDate
WeekNumber 
FROM tablename 
GROUP BY WeekNumber,Store

提前致谢!

4

1 回答 1

2

以下是 BigQuery 标准 SQL

#standardSQL
SELECT strore, 
  DATE_TRUNC(date, WEEK(MONDAY)) StartDate,
  EXTRACT(WEEK(MONDAY) FROM date) WeekNumber,
  COUNT(*) cnt
FROM `project.dataset.table`
GROUP BY strore, StartDate, WeekNumber   

如果适用于您的问题中的示例数据,如下例所示

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 11 store, DATE '2019-11-14' date UNION ALL
  SELECT 11, '2019-11-12' UNION ALL
  SELECT 11, '2019-11-17' UNION ALL
  SELECT 11, '2019-11-15' UNION ALL
  SELECT 11, '2019-11-11' UNION ALL
  SELECT 11, '2019-11-13' UNION ALL
  SELECT 11, '2019-11-16' UNION ALL
  SELECT 11, '2019-11-19' UNION ALL
  SELECT 11, '2019-11-21' UNION ALL
  SELECT 11, '2019-11-22' 
)
SELECT store, 
  DATE_TRUNC(date, WEEK(MONDAY)) StartDate,
  EXTRACT(WEEK(MONDAY) FROM date) WeekNumber,
  COUNT(*) cnt
FROM `project.dataset.table`
GROUP BY store, StartDate, WeekNumber  

输出是

Row store   StartDate   WeekNumber  cnt  
1   11      2019-11-11  45          7    
2   11      2019-11-18  46          3      

更新:在最初的答案中,我错过了要求: start date [should be taken] from the available dates for that week from table

下面的查询正是这样做的:

#standardSQL
SELECT Store, 
  MIN(Date) StartDate,
  WeekNumber,
  COUNT(*) cnt
FROM `project.dataset.table`
GROUP BY Store, WeekNumber     

是否适用于您问题中的 [更新] 示例数据

WITH `project.dataset.table` AS (
  SELECT 11 Store, '2019-11-14' Date, 201953 WeekNumber UNION ALL
  SELECT 11, '2019-11-12', 201953 UNION ALL
  SELECT 11, '2019-11-17', 201953 UNION ALL
  SELECT 11, '2019-11-15', 201953 UNION ALL
  SELECT 11, '2019-11-11', 201953 UNION ALL
  SELECT 11, '2019-11-13', 201953 UNION ALL
  SELECT 11, '2019-11-16', 201953 UNION ALL
  SELECT 11, '2019-11-19', 201954 UNION ALL
  SELECT 11, '2019-11-21', 201954 UNION ALL
  SELECT 11, '2019-11-22', 201954 
)

结果是

Row Store   StartDate   WeekNumber  cnt  
1   11      2019-11-11  201953      7    
2   11      2019-11-19  201954      3    
于 2020-07-27T13:56:37.447 回答