從日期格式中提取年月的方法?


要想從日期格式中提取年份,可以使用 MySQL 自帶的 YEAR() 函式。 查詢如下 −

mysql> SELECT YEAR(curdate()) as OnlyYearFromCurrentDate;

輸出如下 −

+-------------------------+
| OnlyYearFromCurrentDate |
+-------------------------+
| 2018                    |
+-------------------------+
1 row in set (0.00 sec)

也可以用以下方式進行操作 −

mysql> SELECT YEAR(date(now())) as OnlyYearFromCurrentDate;

輸出如下 −

+-------------------------+
| OnlyYearFromCurrentDate |
+-------------------------+
| 2018                    |
+-------------------------+
1 row in set (0.00 sec)

透過這種方式,即使列是 varchar 型別也能實現這個操作。我們先建立一個表 −

mysql> create table ExtractYearDemo
   −> (
   −> YourDueTime varchar(200)
   −> );
Query OK, 0 rows affected (1.15 sec)

使用 insert 命令將記錄插入表中。查詢如下 −

mysql> insert into ExtractYearDemo values('27-10-2011');
Query OK, 1 row affected (0.16 sec)

mysql> insert into ExtractYearDemo values('28-11-2012');
Query OK, 1 row affected (0.15 sec)

mysql> insert into ExtractYearDemo values('29-12-2018');
Query OK, 1 row affected (0.14 sec)

mysql> insert into ExtractYearDemo values('01-01-2019');
Query OK, 1 row affected (0.15 sec)

使用 SELECT 語句顯示錶中的所有記錄。查詢如下 −

mysql> select *from ExtractYearDemo;

輸出如下 −

+-------------+
| YourDueTime |
+-------------+
| 27-10-2011  |
| 28-11-2012  |
| 29-12-2018  |
| 01-01-2019  |
+-------------+
4 rows in set (0.00 sec)

當列為 varchar 型別時,從表列中提取年份的查詢如下 −

mysql> select YEAR(STR_TO_DATE(yourDueTime, "%d-%m-%Y")) As OnlyYearFromDate from ExtractYearDemo;

顯示年份的輸出如下 −

+------------------+
| OnlyYearFromDate |
+------------------+
|             2011 |
|             2012 |
|             2018 |
|             2019 |
+------------------+
4 rows in set (0.00 sec)

更新於: 30-Jul-2019

319 次瀏覽

開啟您的 職業生涯

透過完成課程來獲得認證

立刻開始
廣告
© . All rights reserved.