簡體   English   中英

如何在 MySql/PostgreSQL 中將字符串轉換為日期時間格式

[英]How to convert String into DateTime Format in MySql/PostgreSQL

我有幾列的表,其中一列用於執行編號( exe_number ),它將數據存儲在 varchar(100) 中。

select*from exedetails;
+------------+------------+------------+-------------+
| exe_number | pass_count | fail_count | error_count |
+------------+------------+------------+-------------+
| 02Aug_E1   |         98 |          9 |           0 |
| 31Jul_E1   |         94 |          8 |           1 |
| 30Jul_E2   |         76 |          9 |           3 |
| 01Aug_E2   |         98 |          7 |           0 |
| 02Aug_E2   |         76 |          8 |           2 |
| 30Jul_E1   |         98 |         12 |           9 |
| 31Jul_E2   |         91 |          6 |           1 |
| 01Aug_E1   |         67 |         14 |           2 |
+------------+------------+------------+-------------+
8 rows in set (0.00 sec)

describe exedetails;
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| exe_number  | varchar(100) | YES  |     | NULL    |       |
| pass_count  | int          | YES  |     | NULL    |       |
| fail_count  | int          | YES  |     | NULL    |       |
| error_count | int          | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

這里30/31/01/02是日期, Aug/Jul是一個月, E1/E2是執行迭代(這是為了我的簡單)。

讓我們考慮現在的日期是

'2022 年 8 月 2 日'

所以我想以這樣一種方式編寫一個查詢,所有記錄都以

8月2日_

應該在表的頂部。 意味着它應該根據日期排列,以便當前記錄應該在頂部。

我為此寫的查詢沒有給出預期的結果:

select exe_number from exedetails order by exe_number desc;
+------------+
| exe_number |
+------------+
| 31Jul_E2   |
| 31Jul_E1   |
| 30Jul_E2   |
| 30Jul_E1   |
| 02Aug_E2   |
| 02Aug_E1   |
| 01Aug_E2   |
| 01Aug_E1   |
+------------+
8 rows in set (0.00 sec)

select exe_number from exedetails order by exe_number asc;
+------------+
| exe_number |
+------------+
| 01Aug_E1   |
| 01Aug_E2   |
| 02Aug_E1   |
| 02Aug_E2   |
| 30Jul_E1   |
| 30Jul_E2   |
| 31Jul_E1   |
| 31Jul_E2   |
+------------+
8 rows in set (0.00 sec)

預期結果:

+------------+
| exe_number |
+------------+
| 02Aug_E1   |
| 02Aug_E2   |
| 01Aug_E1   |
| 01Aug_E2   |
| 31Jul_E1   |
| 31Jul_E2   |
| 30Jul_E1   |
| 30Jul_E2   |
+------------+

MySQL/PostgreSQL 中有什么方法可以讓我得到我想要的解決方案嗎?

只需將“日期部分”轉換為適當的date值,然后您就可以對其進行排序:

select *
from exedetails
order by to_date(left(exe_number, 5), 'ddmon') desc, 
         right(exe_number, 2) 

請注意,使用月份名稱to_date()取決於您的區域設置和列中的值。

Postgres 的在線示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM