我有一个包含帐户和订阅金额的表格,或多或少有以下查询:
SELECT FORMAT_DATE(\"%Y-%m\", DATE(receivedOn)) AS Date,
SUM(amount)
FROM `mytablehere`
GROUP BY Date
ORDER BY Date ASC
输出很好但是有些月份没有任何订阅,所以金额为空,并且最终结果中没有返回月份。由于我直接在Google表格中导入结果以从中构建图表,因此没有整整12个月的年份令人讨厌。
有没有办法生成"虚拟"错过月份的月份?回答一个类似的问题建议创建另一个表满月并联合两个表...我正在寻找更简单的东西...
答案 0 :(得分:1)
有没有办法生成"虚拟"错过月份的月份?
下面的示例适用于BigQuery Standard SQL
#standardSQL
WITH `mytablehere` AS (
SELECT '2018-01-01' AS receivedOn, 1 amount UNION ALL
SELECT '2018-01-02' AS receivedOn, 2 amount UNION ALL
SELECT '2018-03-04' AS receivedOn, 4 amount UNION ALL
SELECT '2018-05-10' AS receivedOn, 3 amount UNION ALL
SELECT '2018-05-11', 5
), months AS (
SELECT month FROM (
SELECT
MIN(PARSE_DATE('%Y-%m-%d', receivedOn)) AS min_month,
MAX(PARSE_DATE('%Y-%m-%d', receivedOn)) AS max_month
FROM `mytablehere`
), UNNEST(GENERATE_DATE_ARRAY(min_month, max_month, INTERVAL 1 MONTH)) month
)
SELECT
FORMAT_DATE('%Y-%m', month) AS DATE,
SUM(amount) amount
FROM months
LEFT JOIN `mytablehere`
ON FORMAT_DATE('%Y-%m', PARSE_DATE('%Y-%m-%d', receivedOn)) = FORMAT_DATE('%Y-%m', month)
GROUP BY DATE
ORDER BY DATE ASC
结果为
Row DATE amount
1 2018-01 3
2 2018-02 null
3 2018-03 4
4 2018-04 null
5 2018-05 8