1

就像标题说的那样,我需要有一个最终结果,在一行上我有年月和周......

像这样的东西:

------------------------
| Year | Month | Week  |  
| 2012 |   1   |   1   |  
| 2012 |   1   |   2   |  
| 2012 |   1   |   3   |  
| 2012 |   1   |   4   |  
| 2012 |   1   |   5   |  
| 2012 |   2   |   5   |  

等等...

是否可以生成这样的视图(也使用一些支持表)?

4

2 回答 2

3

您可以使用存储过程来做到这一点:

DELIMITER $$

CREATE PROCEDURE createDatesTable()
BEGIN

DECLARE FullDate date;

DROP TABLE IF EXISTS dates;
CREATE TABLE dates(
date_key date NOT NULL,
calendarYear int NOT NULL,
calendarQuarter tinyint NOT NULL,
calendarMonthNo int NOT NULL,
calendarWeekNo tinyint NOT NULL,
dayNumberOfMonth tinyint NOT NULL,
dayNumberOfWeek tinyint NOT NULL,
PRIMARY KEY (date_key));

SET FullDate  = '2012-01-01';

WHILE (FullDate <= '2012-12-31') DO 
BEGIN

INSERT INTO dates( 
    date_key,
    calendarYear,
    calendarQuarter,
    calendarMonthNo,
    calendarWeekNo,
    dayNumberOfMonth,
    dayNumberOfWeek
)VALUES( 
    FullDate,
    YEAR(FullDate),
    QUARTER(FullDate),
    MONTH(FullDate),
    WEEK(FullDate, 1), /*Have a look at the WEEK() function in the manual!!!*/
    DAYOFMONTH(FullDate),
    DAYOFWEEK(FullDate)
);

SET FullDate = DATE_ADD(Fulldate, INTERVAL 1 DAY);
END;
END WHILE;
END ;
$$
DELIMITER ;

然后做一个call createDatesTable()

你的桌子就会被填满。

重要提示:ypercube 的评论是正确的。你必须考虑到这一点。因此,请查看WEEK() 函数及其支持的模式。相应地调整程序。

于 2012-04-13T11:28:54.113 回答
0

添加为该表的扩展!
如果有人正在寻找如何获取每周的日期范围(第一个日期和最后一个日期),则以下代码将执行此操作:

SELECT date_key AS first_date, MAX(date_key) AS last_date, calendarWeekNo AS week_no 
FROM dates WHERE calendarYear = 2013
GROUP BY `calendarWeekNo`
ORDER BY `calendarWeekNo` ASC

只需将年份更改为您选择的选定年份!上面的例子是2013

结果:

first_date | last_date  | week_no
---------------------------------
2013-01-01 | 2013-01-06 | 1
2013-01-07 | 2013-01-13 | 2
2013-01-14 | 2013-01-20 | 3

etc, etc, etc...
于 2013-06-14T18:49:07.830 回答