我在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)
答案 0 :(得分: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;
答案 1 :(得分: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)