Vi kan bruge MySQL's LAST_DAY()
funktion for at returnere den sidste dag i en given måned.
Dette kan være den sidste dag i den aktuelle måned eller den sidste dag i måneden baseret på en dato, som vi angiver.
Eksempel
SELECT LAST_DAY('2030-04-15');
Resultat:
2030-04-30
I dette tilfælde har den angivne måned (maj) 30 dage, så vi får den 30. i den måned.
Her er den med årets forskellige måneder:
SELECT
LAST_DAY('2030-01-15') AS "Jan",
LAST_DAY('2030-02-15') AS "Feb",
LAST_DAY('2030-03-15') AS "Mar",
LAST_DAY('2030-04-15') AS "Apr",
LAST_DAY('2030-05-15') AS "May",
LAST_DAY('2030-06-15') AS "Jun",
LAST_DAY('2030-07-15') AS "Jul",
LAST_DAY('2030-08-15') AS "Aug",
LAST_DAY('2030-09-15') AS "Sep",
LAST_DAY('2030-10-15') AS "Oct",
LAST_DAY('2030-11-15') AS "Nov",
LAST_DAY('2030-12-15') AS "Dec";
Resultat:
+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+ | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec | +------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+ | 2030-01-31 | 2030-02-28 | 2030-03-31 | 2030-04-30 | 2030-05-31 | 2030-06-30 | 2030-07-31 | 2030-08-31 | 2030-09-30 | 2030-10-31 | 2030-11-30 | 2030-12-31 | +------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+------------+
Databaseeksempel
Her er et eksempel, der bruger datoer fra en database:
CREATE TABLE employees (
empId INTEGER PRIMARY KEY,
name TEXT NOT NULL,
start_date DATE NOT NULL
);
INSERT INTO employees VALUES (0001, 'Rohit', '2020-02-15');
INSERT INTO employees VALUES (0002, 'Zohan', '2017-08-09');
INSERT INTO employees VALUES (0003, 'Jen', '2010-09-03');
INSERT INTO employees VALUES (0004, 'Eve', '2011-10-24');
INSERT INTO employees VALUES (0005, 'Ryan', '2021-11-08');
SELECT
start_date,
CAST(LAST_DAY(start_date) AS DATE) AS "End of Month"
FROM employees;
Resultat:
start_date End of Month 2020-02-15 2020-02-29 2017-08-09 2017-08-31 2010-09-03 2010-09-30 2011-10-24 2011-10-31 2021-11-08 2021-11-30
I dette tilfælde brugte jeg også CAST()
funktion til at caste datetime
værdi til en date
værdi.