就像标题所说,我需要在一条线上得到最终结果 年 - 月和周...
类似的东西:
------------------------
| Year | Month | Week |
| 2012 | 1 | 1 |
| 2012 | 1 | 2 |
| 2012 | 1 | 3 |
| 2012 | 1 | 4 |
| 2012 | 1 | 5 |
| 2012 | 2 | 5 |
等等......
是否可以生成这样的视图(也使用一些支持表)?
答案 0 :(得分: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() function及其支持的模式。相应地调整程序。
答案 1 :(得分: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...