2017-04-18 66 views
0

在這個偉大的article中,我找到了將年份轉換爲十年的方法,但它看起來對我來說太冗長了!BigQuery:如何將年份轉換爲十年?

有沒有更好的方法來做到這一點?

#standardSQL 
WITH data AS (
    SELECT '1921' AS YEAR UNION ALL 
    SELECT '1932' UNION ALL 
    SELECT '1943' UNION ALL 
    SELECT '1954' UNION ALL 
    SELECT '1985' UNION ALL 
    SELECT '2006' UNION ALL 
    SELECT '2017' UNION ALL 
    SELECT '2018' 
) 
SELECT 
    YEAR, 
    CASE 
    WHEN YEAR LIKE "192%" THEN "20S" 
    WHEN YEAR LIKE "193%" THEN "30S" 
    WHEN YEAR LIKE "194%" THEN "40S" 
    WHEN YEAR LIKE "195%" THEN "50S" 
    WHEN YEAR LIKE "196%" THEN "60S" 
    WHEN YEAR LIKE "197%" THEN "70S" 
    WHEN YEAR LIKE "198%" THEN "80S" 
    WHEN YEAR LIKE "199%" THEN "90S" 
    WHEN YEAR LIKE "200%" THEN "2000S" 
    WHEN YEAR LIKE "201%" THEN "2010S" 
    END AS DECADES 
FROM data 
-- ORDER BY YEAR 

回答

1

從年 「提取」 十年 - REGEXP_REPLACE功能可以作爲下面的例子

#standardSQL 
WITH data AS (
    SELECT '1921' AS YEAR UNION ALL 
    SELECT '1932' UNION ALL 
    SELECT '1943' UNION ALL 
    SELECT '1954' UNION ALL 
    SELECT '1985' UNION ALL 
    SELECT '2006' UNION ALL 
    SELECT '2017' UNION ALL 
    SELECT '2028' 
) 
SELECT 
    YEAR, 
    REGEXP_REPLACE(YEAR, r'(?:19)(\d)\d|(20\d)\d', '\\1\\20s') AS DECADES 
FROM data 
-- ORDER BY YEAR 
+0

在爲什麼鑄造'INT64'後不要使用'TRUNC'? –

+0

當然,爲什麼不呢?這是一個選擇。但是當我在回答之前「評估」它的時候 - 我得到的印象是,獲得與文章中完全相同的結果仍然有點羅嗦 - 儘管如此,它可能是偏好問題:o) –

相關問題