拥有一个名为blubb
的表格,其中包含3个字段:id
,year
和week
CREATE TABLE blubb (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`year` int(11) NOT NULL,
`week` int(11) NOT NULL
);
INSERT INTO blubb (year, week) VALUES (2017, 1);
INSERT INTO blubb (year, week) VALUES (2017, 2);
INSERT INTO blubb (year, week) VALUES (2017, 3);
INSERT INTO blubb (year, week) VALUES (2017, 4);
INSERT INTO blubb (year, week) VALUES (2017, 5);
INSERT INTO blubb (year, week) VALUES (2017, 6);
INSERT INTO blubb (year, week) VALUES (2017, 7);
INSERT INTO blubb (year, week) VALUES (2017, 8);
INSERT INTO blubb (year, week) VALUES (2017, 9);
INSERT INTO blubb (year, week) VALUES (2017,10);
INSERT INTO blubb (year, week) VALUES (2017,11);
INSERT INTO blubb (year, week) VALUES (2017,12);
INSERT INTO blubb (year, week) VALUES (2017,13);
INSERT INTO blubb (year, week) VALUES (2017,14);
INSERT INTO blubb (year, week) VALUES (2017,15);
我们的目标是在和之间获得一个选择语句,其中year
和week
与W
连接,这将始终选择两位数的一周。因此,如果周值是1
,我需要01
我是这样完成的:
SELECT DISTINCT
IF(week < 10, CONCAT(year, 'W0', week), CONCAT(year, 'W', week) ) as year_week,
year,
week
FROM
blubb
结果和预期结果:
year_week year week
2017W01 2017 1
2017W02 2017 2
2017W03 2017 3
2017W04 2017 4
2017W05 2017 5
2017W06 2017 6
2017W07 2017 7
2017W08 2017 8
2017W09 2017 9
2017W10 2017 10
2017W11 2017 11
2017W12 2017 12
2017W13 2017 13
2017W14 2017 14
2017W15 2017 15
问题是:还有另一种更好,更清洁的解决方法吗? 谢谢
答案 0 :(得分:1)
使用LPAD:
SELECT
CONCAT(year, 'W', LPAD(week, 2, '0'))as year_week,
year,
week
FROM
blubb
答案 1 :(得分:1)