【问题标题】:How to split the total time with condition如何根据条件拆分总时间
【发布时间】:2011-01-31 18:55:57
【问题描述】:

使用 SQL Server。

表1

ID TotalTime

001 12:00:00
002 11:00:00
003 09:00:00
004 08:00:00
005 14:00:00
....
....,

TotalTime Datatype is nvarchar

我需要将总时间列分成 3 列,如下所示

First 8 Hours should display in  First column
After 8 Hours the next 2 Hours should display in Second column
After 10 Hours the remaining hours should display in third column

预期输出

ID TotalTime Column1 Column2 Column3

001 12:00:00 08:00:00 02:00:00 02:00:00
002 11:00:00 08:00:00 02:00:00 01:00:00
003 09:00:00 08:00:00 01:00:00 
004 08:00:00 08:00:00      
005 14:00:00 08:00:00 02:00:00 04:00:00
....
....,

如何查询上述条件。

需要查询帮助。

【问题讨论】:

  • 第 2 列和第 3 列中的值是否可以接受为 0 而不是 null?
  • 您的 TotalTime 列的类型是什么?不像 nvarchar,我希望...你能给我们看看表定义吗?
  • 1.你的hh:mm:ss 字符串中可以有分钟和秒吗? 2. 小时数可以大于 23 吗?

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


【解决方案1】:

您可以使用case 来划分时间:

select  ID
,       case when totaltime > 8 then 8 
             else totaltime end
,       case when totaltime > 10 then 2
             when totaltime > 8 then totaltime - 8
             else 0 end
,       case when totaltime > 10 then totaltime - 10
             else 0 end
from    YourTable

【讨论】:

  • Nitpick:缺少 TotalTime 列,Gopal 似乎想要nulls 而不是0s——但除此之外:+1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-17
  • 2010-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多