[英]PostgreSQL: Is it possible to sort the part of the string has datetime
I have the name of the column that contains the data sequence and datetime type as shown below:我有包含数据序列和日期时间类型的列的名称,如下所示:
DATA01_0003_20210126135705.zip
DATA01_0003_20210126135705.zip
DATA01_0002_20210127135030.zipDATA01_0002_20210127135030.zip
DATA01_0004_20210126142913.zipDATA01_0004_20210126142913.zip
I want ORDER BY according to datetime, then the sequence string, is it possible?我要根据datetime ORDER BY,然后是sequence string,可以吗?
DATA01_0002_20210127135030.zip
DATA01_0002_20210127135030.zip
DATA01_0004_20210126142913.zipDATA01_0004_20210126142913.zip
DATA01_0003_20210126135705.zipDATA01_0003_20210126135705.zip
I tried the statement like below but it sort in sequence before datetime:我尝试了如下语句,但它在日期时间之前按顺序排序:
SELECT filename FROM tblData ORDER BY filename
DATA01_0002_20210127135030.zip
DATA01_0002_20210127135030.zip
DATA01_0003_20210126135705.zipDATA01_0003_20210126135705.zip
DATA01_0004_20210126142913.zipDATA01_0004_20210126142913.zip
SELECT filename FROM tblData ORDER BY filename DESC
DATA01_0004_20210126142913.zip
DATA01_0004_20210126142913.zip
DATA01_0003_20210126135705.zipDATA01_0003_20210126135705.zip
DATA01_0002_20210127135030.zipDATA01_0002_20210127135030.zip
in postgresql you can sort by expression.在 postgresql 中,您可以按表达式排序。
to sort by the file's timestamp, it is necessary to extract that from the string.要按文件的时间戳排序,有必要从字符串中提取它。 based on your examples, i am going to guess that the text after the last
_
will have the date.根据您的示例,我猜测最后一个
_
之后的文本将具有日期。 if that assumption holds, then the following will sort by date如果该假设成立,那么以下将按日期排序
SELECT filename from tbldata
order by reverse(split_part(reverse(filename), '_', 1))
if the number of _
is fixed, then the trick with two reverse
s is unnecessary.如果
_
的数量是固定的,则不需要使用两个reverse
的技巧。 you can instead order by split_part(filename, '_', 3)
您可以改为
order by split_part(filename, '_', 3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.