从SQL Server 2005中的DateTime减去分钟 [英] Subtract minute from DateTime in SQL Server 2005
问题描述
,其持续时间字段的值为 00:15
如果我减去这两个,我应该得到 2000-01-01 08:15:00
如果我想减去 1:15 (表示1小时15分钟),输出应为 2000-01-01 07: 15:00
我正在尝试 SELECT DATEDIFF(分钟,'00:15','2000-01-01 08: 30:00');
但输出为52595055.如何获得所需的结果?
NB〜如果我做 SELECT dateadd(分钟,-15,'2000-01-01 08:30:00');
,我会获得所需的结果,但这涉及解析分钟字段。
编辑:
根据答案,每个人都建议将所有内容转换成几分钟,然后减去 - 所以如果是1:30,我需要减去90分钟。没关系。任何其他方式,无需转换为分钟?
SELECT DATEADD(minute, '2000-01-01 08:30:00');
第二个值(在这种情况下为-15)必须是数字(即不是像'00 :15')。如果你需要减去几分钟的时间,我建议在以下的字符串中分割字符串:获取小时和分钟,并使用像
SELECT DATEADD(分钟,-60 * @h - @m,'2000-01-01 08:30:00');
其中@h是字符串的小时部分,@m是字符串的小部分
编辑:
这是一个更好的方法:
SELECT CAST('2000-01-01 08:30:00'as datetime) - CAST('00:15'as datetime)
Suppose I have a datetime field whose value is 2000-01-01 08:30:00 and a duration field whose value is say 00:15 (meaning 15 minutes)
If I subtract these two, I should get 2000-01-01 08:15:00
Also if I want to subtract 1:15 (means 1 hour 15 minutes), the output should be 2000-01-01 07:15:00
I am trying SELECT DATEDIFF(minute, '00:15','2000-01-01 08:30:00');
But the output is 52595055. How can i get the desired result?
N.B.~ If I do SELECT dateadd(minute, -15,'2000-01-01 08:30:00');
, I will get the desired result but that involves parsing the minute field.
Edit:
As per the answers, every one is suggesting converting everything into minutes and then to subtract - so if it is 1:30, i need to subtract 90 minutes. That's fine. Any other way without converting to minutes?
SELECT DATEADD(minute, -15, '2000-01-01 08:30:00');
The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like
SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00');
where @h is the hour part of your string and @m is the minute part of your string
EDIT:
Here is a better way:
SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)
这篇关于从SQL Server 2005中的DateTime减去分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!