如何以特定格式显示时间

时间:2011-02-18 05:52:10

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

使用SQL Server 2005

表1

ID TimeColumn

001 13.00
002 03.30
003 14.00
004 23.00
005 08.30
...

<小时/>     表1格式

TimeColumn Format: HH:MM
TimeColumn Datatype is nvarchar
TimeColumn will display the time One Hour or HalfHour
TimeColumn will not display 08.20, 08.56. It will display the time like 08.00, 08.30.

我希望显示的时间为13而不是13.00,3.5而不是03.30。

预期产出

ID   TimeColumn  Value

001  13.00       13
002  03.30       3.5
003  14.00       14
004  23.00       23
005  18.30       18.5
...

如何查询上述情况?

6 个答案:

答案 0 :(得分:2)

根据您的事实,最后3位数只有2个案例,

  • 0.30 ;或
  • 0.00

所以我们只需要替换它们

SELECT
    ID,
    TimeColumn,
    Value = replace(replace(TimeColumn, '.30', '.5'), '.00', '')
From Table1

修改

要删除前导0,您可以使用它(值列为数字)

SELECT
    ID,
    TimeColumn,
    Value = round(convert(float,TimeColumn)*2,0)/2
From Table1

或者如果你需要它是varchar

SELECT
    ID,
    TimeColumn,
    Value = right(round(convert(float,TimeColumn)*2,0)/2,5)
From Table1

答案 1 :(得分:1)

试试这个

SELECT
  DATEPART(hour,TimeColumn) + 
  1 / DATEPART(minute,TimeColumn) * 60 
  AS Value
FROM Table1

这是TimeColumn是DateTime的地方。对于列类型,NVarChar使用字符串函数来分割小时和分钟。

答案 2 :(得分:0)

我相信SQL Server存储日期时间的方式,然后用你的编程语言来格式化它。

答案 3 :(得分:0)

以下是如何做到这一点:

select SUBSTRING('20.30', 1, 2) + (case when SUBSTRING('20.30', 4, 2) = '30' then '.5' else '' end)

只需用您的列名替换'20 .30'并从子句

添加

答案 4 :(得分:0)

Declare @table table (ID nvarchar(10),timevalue nvarchar(10))

INSERT INTO @table values('001','13.00')
INSERT INTO @table values('002','03.30')
INSERT INTO @table values('003','14.00')
INSERT INTO @table values('004','23.00')
INSERT INTO @table values('005','08.30')

select (CASE WHEN (CHARINDEX('.3',timevalue)>0) then convert(varchar(2),timevalue,2) 
        else convert(varchar(2),timevalue,2) + '.5'
end)
from @table

答案 5 :(得分:0)

With TestInputs As
    (
    Select '001' As Id, Cast('13.00' As nvarchar(10)) As TimeColumn
    Union All Select '002','03.30'
    Union All Select '003','14.00'
    Union All Select '004','23.00'
    Union All Select '005','08.30'
    Union All Select '006','08.26'
    Union All Select '007','08.46'
    Union All Select '008','08.56'
    )
    , HoursMinutes As
    (
    Select Id, TimeColumn
        , Cast( Substring(TimeColumn
                    , 1
                    , CharIndex('.', TimeColumn) - 1 ) As int ) As [Hours]
        , Cast( Substring(TimeColumn
                    , CharIndex('.', TimeColumn) + 1
                    , Len(TimeColumn) ) As int ) As [Minutes]
    From TestInputs
    )
Select Id, TimeColumn
    , [Hours] + Case 
                When [Minutes] < 30 Then 0.0
                When [Minutes] < 60 Then 0.5
                Else 1
                End As Value
From HoursMinutes