如何用条件显示时间

时间:2011-02-08 20:16:31

标签: sql sql-server tsql sql-server-2005

使用SQL Server

表1

ID  |  Intime  |   Outtime
--------------------------
001 | 00:21:00 |  00:48:00
002 | 08:14:00 |  13:45:00
003 | 00:34:00 |  00:18:00

时间格式:HH:MM:SS

Tried Code。

SELECT dateadd(mi, datediff(mi,0, Intime)/30*30, 0) AS 'Intime'
  FROM Table1

以上查询给出结果30分钟或1小时,这意味着分钟少于30,然后显示30​​分钟,分钟大于30,然后显示1小时

我需要显示15分钟,30分钟或1小时的时间,它应显示有条件的发送时间

条件

If minutes is less than 15 minutes then it should display exactly 15 Minutes, for example 03:15:00
If minutes is greater than 15 minutes and less than 45 minutes then it should display exactly 30 Minutes, for example 03:30:00
If minutes is greater than 45 minutes then it should display exactly 1 hour, for example 04:00:00

table1的预期输出

ID |银泰| Outtime

001 | 00:30:00 | 01:00:00
002 | 08:15:00 | 14:00:00
003 | 00:30:00 | 00:30:00

如何使用条件查询舍入时间。

需要查询帮助

1 个答案:

答案 0 :(得分:1)

对您的问题的字面解释:

select id,
InTime = DateAdd(mi,
    case
    when DateAdd(hh, -DATEDIFF(HH, 0, intime), intime) = '00:00:00' then 0
    when DateAdd(hh, -DATEDIFF(HH, 0, intime), intime) <= '00:15:00' then 15
    when DateAdd(hh, -DATEDIFF(HH, 0, intime), intime) <= '00:45:00' then 30
    else 60
    end, DateAdd(hh, DATEDIFF(HH, 0, intime), 0)),
OutTime = DateAdd(mi,
    case
    when DateAdd(hh, -DATEDIFF(HH, 0, OutTime), OutTime) = '00:00:00' then 0
    when DateAdd(hh, -DATEDIFF(HH, 0, OutTime), OutTime) <= '00:15:00' then 15
    when DateAdd(hh, -DATEDIFF(HH, 0, OutTime), OutTime) <= '00:45:00' then 30
    else 60
    end, DateAdd(hh, DATEDIFF(HH, 0, OutTime), 0))
from tbl

但是考虑到你的输出,你的第三条规则应该是

  

如果分钟大于[OR EQUAL TO] 45分钟,那么它应该正好显示1小时,例如04:00:00

所以查询变为

select id,
InTime = DateAdd(mi,
    case
    when DateAdd(hh, -DATEDIFF(HH, 0, intime), intime) = '00:00:00' then 0
    when DateAdd(hh, -DATEDIFF(HH, 0, intime), intime) <= '00:15:00' then 15
    when DateAdd(hh, -DATEDIFF(HH, 0, intime), intime) < '00:45:00' then 30
    else 60
    end, DateAdd(hh, DATEDIFF(HH, 0, intime), 0)),
OutTime = DateAdd(mi,
    case
    when DateAdd(hh, -DATEDIFF(HH, 0, OutTime), OutTime) = '00:00:00' then 0
    when DateAdd(hh, -DATEDIFF(HH, 0, OutTime), OutTime) <= '00:15:00' then 15
    when DateAdd(hh, -DATEDIFF(HH, 0, OutTime), OutTime) < '00:45:00' then 30
    else 60
    end, DateAdd(hh, DATEDIFF(HH, 0, OutTime), 0))
from tbl

<小时/>

RE您之前的问题

你接受的答案in your previous quesion总是 ROUNDED DOWN ,当答案有正确的四舍五入时?说明不正确

  

以上查询给出结果30分钟或1小时,这意味着分钟少于30,然后显示30​​分钟

没有。 select dateadd(mi, datediff(mi,0, '09:21')/30*30, 0)返回向下舍入的09:00