透视并获取每个单元格中的行数?

时间:2016-05-13 14:52:04

标签: sql google-bigquery

以下查询为我提供了每张支持服务单的yearmonth_num

SELECT STRFTIME_UTC_USEC(created_at, '%Y') AS year, 
  STRFTIME_UTC_USEC(created_at, '%m') AS month_num
FROM zendesk.zendesk

我想调整年份值并显示每个单元格中所有源行的COUNT(*),如下所示:

    2014    2015    2016
01     5     ...     ...
02     8
03    12
04    22
05    30
06    15
07    10
08     9
09   ...
10
11
12

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

SELECT STRFTIME_UTC_USEC(created_at, '%m') AS month_num,
       SUM(CASE WHEN STRFTIME_UTC_USEC(created_at, '%Y') = '2014' then 1 else 0 end) as cnt_2014,
       SUM(CASE WHEN STRFTIME_UTC_USEC(created_at, '%Y') = '2015' then 1 else 0 end) as cnt_2015,
       SUM(CASE WHEN STRFTIME_UTC_USEC(created_at, '%Y') = '2016' then 1 else 0 end) as cnt_2016
FROM zendesk.zendesk
GROUP BY month_num;

答案 1 :(得分:1)

SELECT
  month_num,
  MIN(CASE WHEN [year] = '2014' THEN cnt END) AS year_2014,
  MIN(CASE WHEN [year] = '2015' THEN cnt END) AS year_2015,
  MIN(CASE WHEN [year] = '2016' THEN cnt END) AS year_2016
FROM (
  SELECT 
    STRFTIME_UTC_USEC(created_at, '%Y') AS [year], 
    STRFTIME_UTC_USEC(created_at, '%m') AS month_num,
    COUNT(*) AS cnt
  FROM zendesk.zendesk
  GROUP BY 1,2
)
GROUP BY 1