gpt4 book ai didi

将字符串转换为时间的SQL函数

转载 作者:行者123 更新时间:2023-12-01 22:04:46 25 4
gpt4 key购买 nike

我有这个字符串:PT0H8M30S。 “H”前的数字代表小时,“M”前的数字代表分钟,“S”前的数字代表秒....如何使用 SQL 函数将其仅转换为分钟?
结果应该是:8.5分钟

非常感谢!!!

最佳答案

我们可以使用 SQL Server 中的基本字符串函数(PATINDEXCHARINDEXSUBSTRING)来解析您的时间字符串。要获得每个单元的结束点,我们可以查找HMS。要获得起点,我们可以查找紧接在特定时间单位之前的一位或两位数字。这会导致一些冗长的 SQL Server 代码,但它对于以任何出现顺序存在/不存在的任何时间单位都相当稳健。

WITH yourTable AS (
SELECT 'PTx10H48M30S' AS string UNION ALL
SELECT 'P2DT3H4M'
)

SELECT
CASE WHEN CHARINDEX('D', string) > 0
THEN
CASE WHEN PATINDEX('%[0-9][0-9]D%', string) > 0
THEN CONVERT(float, SUBSTRING(string, PATINDEX('%[0-9][0-9]D%', string), 2)) * 24 * 60
ELSE CONVERT(float, SUBSTRING(string, PATINDEX('%[0-9]D%', string), 1)) * 24 * 60 END
ELSE 0.0 END
+
CASE WHEN CHARINDEX('H', string) > 0
THEN
CASE WHEN PATINDEX('%[0-9][0-9]H%', string) > 0
THEN CONVERT(float, SUBSTRING(string, PATINDEX('%[0-9][0-9]H%', string), 2)) * 60
ELSE CONVERT(float, SUBSTRING(string, PATINDEX('%[0-9]H%', string), 1)) * 60 END
ELSE 0.0 END
+
CASE WHEN CHARINDEX('M', string) > 0
THEN
CASE WHEN PATINDEX('%[0-9][0-9]M%', string) > 0
THEN CONVERT(float, SUBSTRING(string, PATINDEX('%[0-9][0-9]M%', string), 2))
ELSE CONVERT(float, SUBSTRING(string, PATINDEX('%[0-9]M%', string), 1)) END
ELSE 0.0 END
+
CASE WHEN CHARINDEX('S', string) > 0
THEN
CASE WHEN PATINDEX('%[0-9][0-9]S%', string) > 0
THEN CONVERT(float, SUBSTRING(string, PATINDEX('%[0-9][0-9]S%', string), 2)) / 60
ELSE CONVERT(float, SUBSTRING(string, PATINDEX('%[0-9]S%', string), 1)) / 60 END
ELSE 0.0 END
FROM yourTable;

enter image description here

Demo

关于将字符串转换为时间的SQL函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52493008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com