2016-05-13 59 views
0

以下查詢爲我提供了每張支持票證的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 

我怎樣才能做到這一點?

回答

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
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