How to generate date series to occupy absent dates in google BiqQuery?

后端 未结 5 2155
自闭症患者
自闭症患者 2020-12-03 11:44

I am trying to get daily sum of sales from a google big-query table. I used following code for that.

select Day(InvoiceDate) date, Sum(InvoiceAmount) sales f         


        
5条回答
  •  余生分开走
    2020-12-03 12:21

    For these purposes it is practical to have a 'calendar' table, a table that just lists all the days within a certain range. For your specific question, it would suffice to have a table with the numbers 1 to 31. A quick way to get this table is to make a spreadsheet with these numbers, save it as a csv file and import this file into BigQuery as a table.

    You then left outer join your result set onto this table, with ifnull(sales,0) as sales.

    If you want the number of days per month (28--31) to be right, you basically have two options. Either you create a proper calendar table that covers several years and that you join on using year, month and day. Or you use the simple table with numbers 1--31 and remove numbers based on the month and the year.

提交回复
热议问题