-1

我在 sql server 2012 中编写了一个数据透视查询。它工作正常,它显示了行下的用户名结果和列下的生产时间总和(以秒为单位)。但我需要将秒数拆分为小时:分钟格式。请帮我查询。

declare @empid nvarchar(20), @fromdate date, @todate date, @cols nvarchar(max), @query  AS VARCHAR(MAX), @dt varchar(20), @dt1 varchar(20) 

set @empid = 'EC0100'
set @fromdate = '10/01/13'
set @todate = '10/31/13'
set @dt='Exceptions'
set @dt1='Tech Issues'

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(convert(nvarchar(20),c._Date, 101))
         FROM MIS_BM_Calendar c
         where c._Date between @fromdate and @todate and _Day not in
('Sunday')
         FOR XML PATH(''), TYPE
         ).value('.', 'NVARCHAR(MAX)')
     ,1,1,'')

set @query= 'select UserName, '+@cols+' from 
(select  e.UserName, c._Date , (SUM(DATEDIFF(SS,0,c.TimeTaken))) As TimeTaken
 from MIS_BM_Users e 
 inner join MIS_Opus c 
 on e.EmpId=c.EmpId 
 where (e.AccountManagerID='''+@empid+''') and c.Category not in ('''+@dt+''','''+@dt1+''')
 group by c._Date, e.UserName
) As SourceTable
Pivot
(
SUM(TimeTaken) for _Date in ('+@cols+')
) As Pvt'

execute(@query)
4

2 回答 2

2

一分钟和一小时的秒数是恒定的。一分钟60秒,一小时3600秒。透视查询对此没有影响。

因此,您的问题变成了如何将秒转换为小时、分钟和秒。因为你是 2012 年,所以你有方便的花花公子 TimeFromParts 功能,所以你可以看到你需要喂它小时、分钟和秒

WITH SRC (TimeTaken) AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM sys.all_columns AS AC
)
, Proof AS
(
    -- this logic is valid as long as TimeTaken is less than 24 hours
    -- or 86400 (24 * 60 * 60) seconds
    SELECT 
        SRC.TimeTaken
        -- integer division drops remainder
    ,   SRC.TimeTaken / 3600 AS Hours
        -- integer division and modulo operator to keep legit values
    ,   (SRC.TimeTaken / 60) % 60  AS Minutes
        -- modulo to have values 0 - 59
    ,   SRC.TimeTaken % 60 AS Seconds
    FROM
        SRC
)
SELECT
    P.TimeTaken
,   P.Hours
,   P.Minutes
,   P.Seconds
,   TIMEFROMPARTS(P.Hours, P.Minutes, P.Seconds, 0, 0) AS TimeTakenTimeType
FROM
    Proof AS P;

SQLFiddle

于 2013-11-03T04:52:14.097 回答
1

我创建了一个标量函数并将秒转换为 HHMMSS。然后在主查询中包含该函数。

ALTER function [dbo].[ConvertSecondsToHHMMSS]
(
@TotalSeconds int
)
Returns nvarchar(20)
As
Begin
declare @hours int, @minutes int, @seconds int, @result nvarchar(20)

set @hours = @TotalSeconds / 3600
set @minutes = (@TotalSeconds % 3600) / 60
set @seconds = @TotalSeconds % 60

set @result =  CONVERT(nvarchar(20),@hours) + ':' + CONVERT(nvarchar(20),@minutes) + ':' +CONVERT(nvarchar(20),@seconds)

return @result
end

主要查询:

set @query= 'select UserName, '+@cols+' from
(
select  e.UserName, c._Date, dbo.ConvertSecondsToHHMMSS(SUM(DATEDIFF(SS,0,c.TimeTaken))) As TimeTaken from MIS_BM_Users e 
inner join MIS_Opus c on e.EmpId=c.EmpId 
where (e.AccountManagerID='''+@AccountManagerId+''')
and c.Category not in ('''+@Condition1+''', '''+@condition2+''')
group by c._Date, e.UserName
) As SourceTable
Pivot
(
MIN(TimeTaken) for _Date in ('+@cols+')
) As Pvt'

execute(@query)
于 2013-11-04T05:55:25.220 回答