Generate a Time dimension table in MySQL

Source: Internet
Author: User

Generate a Time dimension table in MySQL

Using the MySQL common date function to generate time dimension tables is the most efficient, simplest, and requires no other tools to support. The resulting results are shown for example:

# time Spanset @d0 = "2012-01-01"; SET @d1 = "2012-12-31"; SET @date = date_sub (@d0, Interval 1 day); # Set up the Time dimension tabledrop TABLE IF EXISTS time_dimension; CREATE TABLE ' time_dimension ' (' date ' date default NULL, ' ID ' int not null, ' y ' smallint default null, ' m ' smallint D Efault null, ' d ' smallint default null, ' yw ' smallint default null, ' W ' smallint default null, ' Q ' smallint default NU  LL, ' WD ' smallint default NULL, ' M_name ' char (TEN) default null, ' Wd_name ' char (TEN) default NULL, PRIMARY KEY (' id ')); # Populate the table with Datesinsert to time_dimensionselect @date: = Date_add (@date, Interval 1 day) as date, # in Teger ID that allowsimmediate understanding date_format (@date, "%y%m%d") as ID, year (@date) as Y, month (@date) as M, Day (@date) as D, Date_format (@date, "%x") as YW, week (@date, 3) as W, quarter (@date) as Q, Weekday (@date) +1 as WD, MonthName (@date) as M_name, Dayname (@date) as Wd_namefrom twhere Date_add (@date, INterval 1 day) <= @d1ORDER by date; 


The mysterious table T, just need more than the number of records you need to generate a date. The idea is to select multiple rows of data from the T table and produce the corresponding date fields.

Generate a Time dimension table in MySQL

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.