如何从日期列表中检索所有唯一(年,季)组合?

时间:2016-10-17 09:44:21

标签: sql google-bigquery

这可以作为一个魅力,从我的表中检索所有唯一(年,月)组合:

SELECT
  STRFTIME_UTC_USEC(TIMESTAMP_TO_USEC(Date), '%Y-%m') as month,
FROM
  [Table] 

返回2016-05,2016-06,2016-07等

想要为(年,季)做同样的事情但却一无所获。有小费吗?我知道季度在sql上非常棘手。谢谢!

2 个答案:

答案 0 :(得分:0)

将QUARTER功能与YEAR功能结合使用:

select concat(string(year(timestamp)),'-Q',string(quarter(timestamp))) as mquerter
from [table]
group by 1

答案 1 :(得分:0)

为了完整起见,您可以使用standard SQL(取消选中用户界面中“显示选项”下的“使用旧版SQL”):

SELECT DISTINCT EXTRACT(YEAR FROM t), EXTRACT(QUARTER FROM t)
FROM MyTable;

例如:

WITH MyTable AS (
  SELECT t
  FROM UNNEST([TIMESTAMP '2016-01-01',
               TIMESTAMP '2016-04-03',
               TIMESTAMP '2016-02-28',
               TIMESTAMP '2017-06-25']) AS t
)
SELECT DISTINCT
  EXTRACT(YEAR FROM t) AS year,
  EXTRACT(QUARTER FROM t) AS quarter
FROM MyTable;
+------+---------+
| year | quarter |
+------+---------+
| 2016 | 1       |
| 2016 | 2       |
| 2017 | 2       |
+------+---------+