我有一个 SQL 列,其中有几个格式为“3 天 18 小时 51 分钟”的字段。我希望有人可以帮助将该持续时间更改为普通数字字段,例如 5451 作为值。请帮忙!
我尝试过分别提取分钟、天和小时,但当小时是单个数字而不是两位数字时,有时定位会关闭。
一种方法是建立一个
"<digits> <keyword>"
模式字符串表来识别和提取组成部分。如果该表中包含 multipler,则提取值、将其转换为整数、应用适当的乘数并对结果求和并不困难。
以下代码将模式表编码为
VALUES
构造,并使用多个 CROSS APPLY
来构建结果。
SELECT *
FROM Data D
CROSS APPLY (
SELECT
SUM(PAT.Multiplier * V.Value) AS Minutes
--*
FROM (
VALUES
-- The leading space is critical to the parse.
-- Optional trailing 's' and trailing '.' are ignored
-- Limits: 5 max digits for year, 2 max digits for hour and minute.
('% [0-9][0-9][0-9][0-9][0-9] Day%', 5, 1440),
('% [0-9][0-9][0-9][0-9] Day%', 4, 1440),
('% [0-9][0-9][0-9] Day%', 3, 1440),
('% [0-9][0-9] Day%', 2, 1440),
('% [0-9] Day%', 1, 1440),
('% [0-9][0-9] Hour%', 2, 60),
('% [0-9] Hour%', 1, 60),
('% [0-9][0-9] Minute%', 2, 1),
('% [0-9] Minute%', 1, 1)
) PAT(Pattern, Digits, Multiplier)
CROSS APPLY (
SELECT PATINDEX(PAT.Pattern, ' ' + D.DateText) AS Pos
) PI
CROSS APPLY (
SELECT CONVERT(INT, SUBSTRING(D.DateText, PI.POS, PAT.Digits)) AS Value
) V
WHERE PI.Pos > 0 -- Match found
) C
结果(带有一些额外的样本数据):
身份证 | 日期文本 | 分钟 |
---|---|---|
1 | 3天18小时51分钟。 | 5451 |
2 | 3天51分钟。 | 4371 |
3 | 18 小时。 | 1080 |
4 | 1天1小时1分钟。 | 1501 |
5 | 10000天1小时1分钟。 | 14400061 |
6 | 未定义 | 空 |
参见这个数据库<>小提琴。