视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
GenerateSeriesinRedshiftandMySQL_MySQL
2020-11-09 19:18:22 责编:小采
文档
 A lot of the charts and tables made inPeriscopeare time series, and the queries behind them are often easier when you can join and aggregate against a list of dates. Not having a complete list of dates causes gaps in the results, changing them in a misleading way:

Postgres has a great function for generating a list of dates (seeUse generate_series to get continuous results), and making a list of the last 60 days withgenerate_seriesis easy:

select now()::date - generate_series(0, 59)

Accomplishing the same thing in Redshift and MySQL requires a little more work.

Date Series from a Numbers Table

The simplest alternative togenerate_seriesis to create a table containing a continuous list of numbers, starting at 0, and select from that table. (If you have a table with a sequentialidcolumn and never delete rows from it, you can just select theidcolumn from that table instead of creating a new numbers table).

select n from numbers;

Returns this list of rows: 0, 1, 2, 3...

Now that you have a numbers table, convert each number into a date:

Redshift:

select (getdate()::date - n)::date from numbers

MySQL:

select date_sub(date(now()), interval n day) from numbers

A numbers table is more convenient than a dates table since it never needs to be refreshed with new dates.

Redshift: Date Series using Window Functions

If you don't have the option to create a numbers table, you can build one on the fly using a window function. All you need is a table that has at least as many rows as the number of dates desired. Using a window function, number the rows in any table to get a list of numbers, and then convert that to a list of dates:

select row_number() over (order by true) as nfrom users limit 60

And now creating the list of dates directly:

select (getdate()::date - row_number() over (order by true))::date as nfrom users limit 60

MySQL: Date Series using Variables

With variables in MySQL, we can generate a numbers table by treating a select statement as a for loop:

set @n:=-1;select (select @n:= @n+1) nfrom users limit 60

And now creating the list of dates directly:

set @n:=date(now() + interval 1 day);select (select @n:= @n - interval 1 day) nfrom users limit 60

Now that we've made a list of dates, aggregating and joining data from other tables for time series charts is a breeze!

下载本文
显示全文
专题