Click here to Skip to main content
15,888,301 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have written a pivot query in sql server 2012. It works fine and it shows the result of usernames under Rows and sum of production hours in seconds under columns. But I need the seconds to be splitted into hours:minutes format. Please help me on query.

SQL
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)
Posted
Comments
RedDk 1-Nov-13 12:43pm    
Instead of "SUM(DATEDIFF(SS,0,c.TimeTaken)))" use "SUM(DATEDIFF(DD,0,c.TimeTaken)))"
Look here in the BOL:
ms-help://MS.SQLCC.v10/MS.SQLSVR.v10.en/s10de_6tsql/html/eba979f2-1a8d-4cce-9d75-b74f9b519b37.htm

1 solution

I have created a scalar function and converted the seconds to HHMMSS. Then include the function in the main query.

SQL
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



Main Query:

SQL
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)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900