Need help returning data in defined buckets - sql

declare #dateto as datetime
set #dateto='8/1/11'
SELECT ti.userkey, SUM(l.Price * l.OrderQty) AS SumOfOrders, count (distinct ti.orderid) AS Ordercount
FROM SOLine AS l WITH (nolock) LEFT OUTER JOIN
SOImported AS ti ON ti.OrderId = l.OrderId LEFT OUTER JOIN
Sale AS o ON o.SaleId = ti.Inventory_Id
Where ti.createddate < #DateTo
GROUP BY ti.userkey, o.WootSiteId
Need this query to bucket order count like the following:
Group userkeycount sumoforders
1 trans
2-30
31-60
61-90
91-120
121-150
151-180
181-210
211-240
241-270
271-300
301-330
331-360
360 or More

declare #dateto as datetime
set #dateto='8/1/11'
SELECT
CASE WHEN Ordercount >= 360 THEN '360 or More'
WHEN Ordercount = 1 THEN '1 trans'
ELSE CAST (30 * FLOOR(Ordercount / 30) AS VARCHAR) + '-' + CAST (30 * CEILING (Ordercount / 30) AS VARCHAR)
END grp,
COUNT(*) userkeycount,
SUM(SumOfOrders) SumOfOrders
FROM (
SELECT ti.userkey,
SUM(l.Price * l.OrderQty) AS SumOfOrders,
count (distinct ti.orderid) AS Ordercount
FROM SOLine AS l WITH (nolock) LEFT OUTER JOIN
SOImported AS ti ON ti.OrderId = l.OrderId LEFT OUTER JOIN
Sale AS o ON o.SaleId = ti.Inventory_Id
Where ti.createddate < #DateTo
GROUP BY ti.userkey
) rs
GROUP BY CASE WHEN Ordercount >= 360 THEN '360 or More'
WHEN Ordercount = 1 THEN '1 trans'
ELSE CAST (30 * FLOOR(Ordercount / 30) AS VARCHAR) + '-' + CAST (30 * CEILING (Ordercount / 30) AS VARCHAR)
END

I have made some changes in The Scrum Meister's query... below you can see the result.
create table #T (ID int identity(0,1) primary key, Ordercount int)
insert #T (Ordercount) values (1)
insert #T (Ordercount) values (2)
insert #T (Ordercount) values (5)
insert #T (Ordercount) values (30)
insert #T (Ordercount) values (37)
insert #T (Ordercount) values (60)
insert #T (Ordercount) values (61)
insert #T (Ordercount) values (360)
insert #T (Ordercount) values (361)
select Ordercount,
CASE WHEN Ordercount > 360 THEN '360 or More'
WHEN Ordercount = 1 THEN '1 trans'
WHEN Ordercount <= 30 THEN '2-30'
ELSE
CAST (30*FLOOR(case when Ordercount%30 = 0 then Ordercount-1 else Ordercount end/30)+1 AS VARCHAR)
+ '-' +
CAST (30*FLOOR(case when Ordercount%30 = 0 then Ordercount-1 else Ordercount end/30)+30 AS VARCHAR)
END
from #T

Related

PIVOT Attendance

I have an attendance table with the result as shown below
I need to get the result in below format:
Below is sample PIVOT query I used. Please help me with a query to get the desired result.
CREATE TABLE #Temp
(
[empcode] varchar(15),
[empDesc] nvarchar(300),
[hrlog_Date] date,
[hrlog_in] datetime,
[hrlog_Out] datetime,
[hrlog_Latein] datetime,
[hrlog_EarlyOut] datetime,
)
DECLARE #Start datetime,#End datetime,#DList varchar(2000),#Sql varchar(max),#Sql1 varchar(max);
SET #Start=#StartDate;
SET #End=#EndDate;
INSERT INTO #Temp
Select h.emp_code,e.emp_desc as emp_Desc,h.hrlog_Date, CONVERT(datetime,h.hrlog_in, 105) as hrlog_in
,CONVERT(datetime,h.hrlog_out,105) as hrlog_out
,
case when cast(h.hrlog_in as time)> cast('8:45' as time) then
cast(h.hrlog_Date as NVARCHAR(50))+' ' +CAST(DATEDIFF(second, cast('8:45' as time), cast(h.hrlog_in as time) ) / 60 / 60 % 24 AS NVARCHAR(50))+ ':' +
CAST(DATEDIFF(second,cast('8:45' as time), cast(h.hrlog_in as time) ) / 60 % 60 AS NVARCHAR(50))
else cast(h.hrlog_Date as nvarchar(50)) +' 0:00' end
mrngLate
,case when cast(h.hrlog_out as time) < cast('17:15' as time) then
cast(h.hrlog_Date as NVARCHAR(50))+' ' +CAST(DATEDIFF(second, cast(h.hrlog_out as time), cast('17:15' as time) ) / 60 / 60 % 24 AS NVARCHAR(50))+ ':' +
CAST(DATEDIFF(second, cast(h.hrlog_out as time),cast('17:15' as time) ) / 60 % 60 AS NVARCHAR(50))
else cast(h.hrlog_Date as nvarchar(50)) +' 0:00' end EvenEarly
from HRDailyLog h INNER JOIN FTEmployee e ON h.emp_code=e.Emp_Code
LEFT OUTER JOIN sys_CostCenterDep c ON e.sys_ccdepcode = c.sys_ccDepCode
LEFT OUTER JOIN FTJobDesc j ON e.job_code = j.Job_code
LEFT OUTER JOIN sysDep d ON j.sys_depcode = d.Sys_Depcode
LEFT OUTER JOIN HrShift s ON e.SFT_Code = s.SFT_Code
Where (h.hrlog_date between #Start and #End and e.SFT_Code is not null)
and CASE WHEN #sftCode = '-1' then #sftCode else e.SFT_Code end= #sftCode
and CASE WHEN #depCode = '-1' then #depCode else d.Sys_Depcode end= #depCode
and h.sys_bRcode = #brCode
SELECT DATEADD(dd,number,#Start) AS Date INTO #Date
FROM master..spt_values
WHERE type='p'
AND DATEADD(dd,number,#Start)<=#End
SELECT #DList=LEFT(dl.Dates,LEN(dl.Dates)-1)
FROM
(SELECT CAST(Date as varchar(11)) + ','
FROM #Date
FOR XML PATH('')
)dl(Dates)
SET #Sql='SELECT * FROM (
SELECT d.Date as dateIn ,t.empcode as empcode,t.empDesc as empDesc,(CONVERT(nvarchar(5),t.hrlog_in, 108)+'' to ''+CONVERT(nvarchar(5),t.hrlog_Out, 108)) as hrlog_in
FROM #Date d
LEFT JOIN #Temp t
ON CONVERT(nvarchar(10), t.hrlog_in, 111)=d.Date
)tm
PIVOT (MIN(hrlog_in) FOR dateIn IN ([' + REPLACE(#DList,',','],[')+ ']))p
WHERE empcode IS NOT NULL'
EXEC(#Sql)

Split the overlapping time in SQL

I have a requirement to equally split the duration for records which has overlapping in the datetime.
Example:
As per the example, if I calculate total runtime of the machine for Order 1, it is 3 hours. But I want it to be 2 hours because in the same machine another order ran between that duration (From 9 AM to 11 AM).
I tried searching the form, and all are pointed to exclude the overlapping duration or doing some other functionality. But I want to split the overlapping duration for all the records.
Sample Table Structure:
declare #st datetime, #et datetime;
DECLARE #table TABLE (Machine varchar(4),OrderId varchar(6),StartTime DateTime2, EndTime DateTime2)
INSERT INTO #table SELECT 'M2','ORD1','2017-11-01 10:30:00.000', '2017-11-01 12:00:00.000'
INSERT INTO #table SELECT 'M2','ORD2','2017-11-01 11:00:00.000', '2017-11-01 12:30:00.000'
INSERT INTO #table SELECT 'M2','ORD3','2017-11-01 11:30:00.000', '2017-11-01 13:00:00.000'
Expected Result:
Expected Result
Based on the above picture,
Duration for ORD1 = 30 MIN + 15 MIN (30 MIN overlap between ORD1 and ORD2) + 10 MIN (30 MIN overlap between ORD1, ORD2 and ORD3)
Duration for ORD2 = 15 MIN + 10 MIN + 15 MIN
Duration for ORD3 = 10 MIN + 15 MIN + 30 MIN
Total Machine Run time will be 55 + 40 + 55 = 150 MIN (2 Hours and 30 MIN)
Thanks,
Aravinth
You should be able to use "window functions" to determine the overall span then divide by number of orders processed, along these lines:
select
machine, order, datetime_start, datetime_end
, min(datetime_start) over(partition by machine, order, date(datetime_start)) min_dt
, max(datetime_start) over(partition by machine, order, date(datetime_start)) max_dt
, count(*) over(partition by machine, order, date(datetime_start)) num
, datediff(ss,min(datetime_start) over(partition by machine, order, date(datetime_start))
,max(datetime_start) over(partition by machine, order, date(datetime_start)))
/ count(*) over(partition by machine, order) as equal_duration
from (
select * from your_query here
)
For more; we would need much more detail from you.
Thanks for all the response. Finally this scenario has been covered with the help of one of our team member. Below is the solution,
DECLARE #table TABLE (OrdId varchar(12),MId varchar(4), ST DateTime, ET DateTime)
INSERT INTO #table SELECT '10001','M1','2017-11-01 10:30:00.000', '2017-11-01 12:00:00.000' INSERT INTO #table SELECT '10002','M1','2017-11-01 11:00:00.000', '2017-11-01 12:30:00.000' INSERT INTO #table SELECT '10003','M1','2017-11-01 11:30:00.000', '2017-11-01 14:00:00.000' INSERT INTO #table SELECT '10004','M2','2017-11-01 14:30:00.000', '2017-11-01 16:00:00.000'
DECLARE #ST datetime, #ET datetime, #NEXT_ST datetime, #RC smallint, #MCHr smallint; set #MCHr = 0; set #ST = (select MIN(ST) AS ST from #table where MId = 'M1' and OrdId = '10001') set #ET = (select MAX(ET) AS ET from #table where MId = 'M1' and OrdId = '10001') WHILE #ST < #ET BEGIN
set #NEXT_ST = (select MIN(ST) AS ST from #table where MId = 'M1' and ST > #ST)
if #NEXT_ST is not null
begin
set #RC = ( SELECT count(*) from #table where MId = 'M1' and (#ST >= ST and #ST < #NEXT_ST))
if #RC > 0
begin
SET #MCHr = #MCHr + (select DATEDIFF(MI,0,#NEXT_ST-#ST) / #RC);
end;
set #ST = #NEXT_ST;
end;
else
begin
set #NEXT_ST = (select MIN(ET) AS ET from #table where MId = 'M1' and (#ST >= ST and #ST < ET))
set #RC = ( SELECT count(*) from #table where MId = 'M1' and (#ST >= ST and #ST < ET))
if #RC > 0
SET #MCHr = #MCHr + (select DATEDIFF(MI,0,#NEXT_ST-#ST) / #RC)
set #ST = #NEXT_ST;
end; END; select #MCHr as MCHr

Multi Day Values

I am having some troubles with my query. I am trying to get the total import rate for the current day, while also matching up the previous day with the correlating hour.
Example: 1AM (Current Day) = 20
1AM(Yesterday) = 25.
As of right now the columns Current and Yesterday are showing identical values.
SELECT
z.[import Hour],
COUNT(z.orderno) as CurrentDate,
COUNT(od.orderno) as Yesterday
FROM (
(select datepart(hh, recvtime) as [import Hour],
orderno
from mck_hvs.orderheader with (nolock)
where convert(date, recvtime) = convert(date, getdate())
and orderno not like '%ST'
UNION
select datepart(hh, recvtime) as [import Hour],
orderno from mck_hvs.oldorderheader with (nolock)
where convert(date, recvtime) = convert(date, getdate())
and orderno not like '%ST' ) as z
Join
(
select datepart(hh, od.recvtime) as [import Hour],
od.orderno from mck_hvs.oldorderheader od with (nolock)
where convert(date, od.recvtime) = convert(date, getdate()-1)
and od.orderno not like '%ST' ) as OD
ON z.[import Hour] = od.[import Hour] )
group by z.[import Hour]
If you use following data:
DECLARE #Orders AS TABLE(OrderNo INT,OrderTaken datetime)
INSERT INTO #Orders VALUES(123,'2017-07-24 12:20:24')
INSERT INTO #Orders VALUES(124,'2017-07-24 12:30:24')
INSERT INTO #Orders VALUES(125,'2017-07-24 13:40:24')
INSERT INTO #Orders VALUES(126,'2017-07-24 13:50:24')
INSERT INTO #Orders VALUES(227,'2017-07-25 12:20:24')
INSERT INTO #Orders VALUES(228,'2017-07-25 12:30:24')
INSERT INTO #Orders VALUES(229,'2017-07-25 13:40:24')
INSERT INTO #Orders VALUES(220,'2017-07-25 13:50:24')
with output:
The following SQL:
DECLARE #Date DATETIME='2017-07-25'
;WITH today AS(
SELECT Cast(OrderTaken As Date) oDate,
CASE WHEN DATEPART(hh,OrderTaken) > 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)-12) + ' PM' WHEN DATEPART(hh,OrderTaken) = 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)) + ' PM' WHEN DATEPART(hh,OrderTaken) < 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)) + ' AM' END As oHour,
Count(OrderNo) OrderCountToday FROM #Orders
WHERE CAST(OrderTaken AS DATE)=CAST(#Date AS DATE)
GROUP BY Cast(OrderTaken As Date),DATEPart(Hour,OrderTaken)
)
,yesterday AS(
SELECT Cast(OrderTaken As Date) oDate,
CASE WHEN DATEPART(hh,OrderTaken) > 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)-12) + ' PM' WHEN DATEPART(hh,OrderTaken) = 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)) + ' PM' WHEN DATEPART(hh,OrderTaken) < 12 THEN CONVERT(VARCHAR(2),DATEPART(hh,OrderTaken)) + ' AM' END As oHour,
Count(OrderNo) OrderCountYesterday
FROM #Orders
WHERE CAST(OrderTaken AS DATE)=CAST(#Date-1 AS DATE)
GROUP BY Cast(OrderTaken As Date),DATEPart(Hour,OrderTaken)
)
SELECT t.oDate Today,t.oHour Hour,t.OrderCountToday,y.OrderCountYesterday FROM today t join yesterday y ON t.oHour=y.oHour and t.oDate=dateadd(day,1,y.oDate)
will result as:
p.s.: You can summarize this SQL a lot if you don't want to use AM/PM thing in the hour. Even the logic for AM/PM can be summarized further but that will show 12 PM as 0 PM.
Hope this help.
I've included a bit of code up front just to generate some test data. You probably won't need it, but others might.
USE sandbox
GO
--------------------------------------------------------------------------------------------
--Recreate the OP's environment in my sandpit
DROP TABLE IF EXISTS mck_hvs.orderheader --2016 syntax
create table mck_hvs.orderheader(
recvtime datetime NOT NULL
,orderno varchar(20) NOT NULL
)
;
ALTER TABLE mck_hvs.orderheader
ADD CONSTRAINT PK_mck_hvs_orderheader_orderno PRIMARY KEY CLUSTERED (orderno)
;
GO
--------------------------------------------------------------------------------------------
DROP TABLE IF EXISTS mck_hvs.oldorderheader
;
create table mck_hvs.oldorderheader(
recvtime datetime NOT NULL
,orderno varchar(20) NOT NULL
)
;
ALTER TABLE mck_hvs.oldorderheader
ADD CONSTRAINT PK_mck_hvs_oldorderheader_orderno PRIMARY KEY CLUSTERED (orderno)
;
GO
--------------------------------------------------------------------------------------------
--Generate some test data (about two years worth working back from today)
--First the old data (not today's)
INSERT mck_hvs.oldorderheader
SELECT top 100000 dateadd(mi,abs(checksum(newid())) %1440,dateadd(dd,-abs(checksum(newid())) %720,getdate()-1)) as recvtime
,right('0000000' + cast(row_number() OVER(ORDER BY (SELECT NULL)) as varchar(20)),7)
+ char(82 + abs(checksum(newid()))%4) + char(82 + abs(checksum(newid()))%4) as orderno--add two random chars from R,S,T,U to the end
FROM sys.columns col1
cross join sys.columns col2
;
--Now today's (assume 500 orders came in)
INSERT mck_hvs.orderheader
SELECT top 500 dateadd(mi,abs(checksum(newid())) %1440,dateadd(dd,datediff(dd,0,getdate()),0)) --add a random number of minutes to midnight last night
,right('0000000' + cast(row_number() OVER(ORDER BY (SELECT NULL)) +100000 as varchar(20)),7)
+ char(82 + abs(checksum(newid()))%4) + char(82 + abs(checksum(newid()))%4) --add two random chars from R,S,T,U to the end
FROM sys.columns col1
cross join sys.columns col2
;
--------------------------------------------------------------------------------------------
WITH yesterday /*all my problems seemed so far away*/as
(
SELECT datepart(hour,old.recvtime) as received_hour
,count(*) as orders_received
FROM mck_hvs.oldorderheader as old
WHERE old.recvtime < dateadd(dd,datediff(dd,0,getdate()),0) --Yesterday
AND old.recvtime >= dateadd(dd,datediff(dd,0,getdate())-1,0)
AND old.orderno not like '%ST' --Note: This is not a SARGable search.
GROUP BY datepart(hour,recvtime)
)
, today as
(
SELECT datepart(hour,ordr.recvtime) as received_hour
,count(*) as orders_received
FROM mck_hvs.orderheader as ordr
WHERE ordr.orderno not like '%ST' --Google "SARG". Trust me.
GROUP BY datepart(hour,ordr.recvtime)
)
SELECT isnull(yesterday.received_hour,today.received_hour) as received_hour
,isnull(yesterday.orders_received,0) as orders_received_yesterday
,isnull(today.orders_received,0) as orders_received_today
FROM yesterday
--FULL JOIN in case there are hours of activity in one table that don't exist in the other table.
FULL JOIN today ON yesterday.received_hour = today.received_hour
;

SQL - possible pivot issue

I have a table with the following structure
Item Id, Start Date, End Date
1 , 2015-01-01, 2015-06-01
2 , 2015-01-01, 2015-02-01
3 , 2015-03-01, 2015-08-01
4 , 2015-06-01, 2015-10-01
I would like to view results so i will have each month in the column.
Each row will contain the id of the item that is within this month.
Example:
I am asking for all items that are within 2015-01-01 to 2015-03-01.
The results should display, in columns, all the months within that range. So in this case it's 3 columns, Jan Feb and March.
The number of rows will be the total number of items that are within that range BUT each cell should show value of item id only if that item is within range:
example:
2015-01-01, 2015-02-01, 2015-03-01
1 1 1
2 2 NULL
NULL NULL 3
In order to use pivot, you can create a recursive cte get each item id and the list of months it covers, then pivot the cte.
;WITH cte AS
(
SELECT [Item Id], [Start Date], [End Date]
FROM Table1
WHERE [Start Date] BETWEEN '2015-01-01' AND '2015-03-01' --Date Range you want
OR [End Date] BETWEEN '2015-01-01' AND '2015-03-01' --Date Range you want
UNION ALL
SELECT [Item Id], DATEADD(MONTH, 1, [Start Date]), [End Date]
FROM cte
WHERE DATEADD(MONTH, 1, [Start Date]) <= [End Date]
)
SELECT [2015-01-01],[2015-02-01],[2015-03-01] --List of Dates you want
FROM (
SELECT [Item Id] rn, -- need a unique id here to give one row per record
[Item Id],
CONVERT(VARCHAR(10), [Start Date], 120) [Start Date] -- Format date to yyyy-mm-dd
FROM cte
) t
PIVOT
( MAX([Item Id])
FOR [Start Date] IN ([2015-01-01],[2015-02-01],[2015-03-01])
) p
You most likely need to use dynamic SQL.
This is your data:
declare #first date = '20150101';
declare #last date = '20150301';
Create Table #items(ItemId int, StartDate date, EndDate date);
Insert into #items(ItemId, StartDate, EndDate) values
(1, '2015-01-01', '2015-06-01')
, (2, '2015-01-01', '2015-02-01')
, (3, '2015-03-01', '2015-08-01')
, (4, '2015-06-01', '2015-10-01');
You first need to get the range of values and columns:
declare #values varchar(max);
declare #cols varchar(max);
with range(d) as (
Select top(DATEDIFF(month, #first, #last)+1) cast(DATEADD(month, ROW_NUMBER() over(order by (select 0))-1, #first) as varchar(20))
From (
Select 1 From (values(1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) as x1(n)
Cross Join (values(1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) as x2(n)
) as x(n)
)
Select #values = coalesce(''+#values+ ', ', ' ') + '('''+d+''')'
, #cols = coalesce(''+#cols+ ', ', ' ') + '['+left(DATENAME(month, d), 3)+CAST(year(d) as char(4))+']'
From range
;
This basically create a row for each date between #first and #last and concatenate them with parenthesis and commas (#values) or brackets (#cols).
Content in #values and #cols look like this:
#values = ('2015-01-01'), ('2015-02-01'), ('2015-03-01')
#cols = [Jan2015], [Feb2015], [Mar2015]
You then create a SQL script using theses 2 variables:
declare #sql nvarchar(max);
Set #sql = '
Select *
From (
Select i.ItemId, d = left(DATENAME(month, r.d), 3)+CAST(year(r.d) as char(4))
, id = case when r.d >= i.StartDate and r.d <= i.EndDate then i.ItemId end
From (values'+#values+') as r(d)
Cross Join (Select ItemId, StartDate, EndDate From #items
Where (#first >= StartDate and #first <= EndDate) or (#last >= StartDate and #last <= EndDate)
) i
) as dates
Pivot (
min(id)
For d in('+#cols+')
) as piv
';
This is the pivot query.
Created SQL will look like this in this example:
Select *
From (
Select i.ItemId, d = left(DATENAME(month, r.d), 3)+CAST(year(r.d) as char(4))
, id = case when r.d >= i.StartDate and r.d <= i.EndDate then i.ItemId end
From (values ('2015-01-01'), ('2015-02-01'), ('2015-03-01')) as r(d)
Cross Join (Select ItemId, StartDate, EndDate From #items
Where (#first >= StartDate and #first <= EndDate) or (#last >= StartDate and #last <= EndDate)
) i
) as dates
Pivot (
min(id)
For d in( [Jan2015], [Feb2015], [Mar2015])
) as piv
You can finally execute the script:
exec sp_executesql #sql, N'#first date, #last date', #first, #last;
Ouput:
ItemId Jan2015 Feb2015 Mar2015
1 1 1 1
2 2 2 NULL
3 NULL NULL 3
Probably something like....
Select
CASE WHEN EXISTS (SELECT 1 FROM TableName where Month(Start) = 1 AND ItemId = t.ItemId) THEN t.ItemId END AS [2015-01-01]
,CASE WHEN EXISTS (SELECT 1 FROM TableName where Month(Start) = 2 AND ItemId = t.ItemId) THEN t.ItemId END AS [2015-02-01]
,CASE WHEN EXISTS (SELECT 1 FROM TableName where Month(Start) = 3 AND ItemId = t.ItemId) THEN t.ItemId END AS [2015-03-01]
,CASE WHEN EXISTS (SELECT 1 FROM TableName where Month(Start) = 4 AND ItemId = t.ItemId) THEN t.ItemId END AS [2015-04-01]
,CASE WHEN EXISTS (SELECT 1 FROM TableName where Month(Start) = 5 AND ItemId = t.ItemId) THEN t.ItemId END AS [2015-05-01]
,CASE WHEN EXISTS (SELECT 1 FROM TableName where Month(Start) = 6 AND ItemId = t.ItemId) THEN t.ItemId END AS [2015-06-01]
,CASE WHEN EXISTS (SELECT 1 FROM TableName where Month(Start) = 7 AND ItemId = t.ItemId) THEN t.ItemId END AS [2015-07-01]
,CASE WHEN EXISTS (SELECT 1 FROM TableName where Month(Start) = 8 AND ItemId = t.ItemId) THEN t.ItemId END AS [2015-08-01]
,..... and so on..... for all the other months...
from TableName t

How to sum set of period times in specific format

If I have result set like that :
Work_hour(hh:mm)
10:24
12:59
06:28
where Work_hour is of type varchar
How to sum those hours and minutes with the same format ?
SELECT CAST(FLOOR(TMP1.MINS/60) AS VARCHAR) + ':' + CAST((TMP1.MINS % 60) AS VARCHAR) FROM (
SELECT SUM (CAST(LEFT(time_column, 2) AS INT) * 60 + CAST(RIGHT(time_column, 2) AS INT)) as MINS FROM table1
) AS TMP1
Where time_column is the column in the table and table1 is the name of the table. Example:
create table table1 (
time_column varchar(10)
);
insert into table1 (time_column) values ('12:20'), ('10:40'), ('15:50');
Results in: 38:50
Try this one -
Query:
DECLARE #temp TABLE
(
work_hour CHAR(5)
)
INSERT INTO #temp (work_hour)
VALUES
('10:24'),
('12:59'),
('06:28')
;WITH cte AS
(
SELECT mn = SUM(DATEDIFF(MINUTE, '19000101', CAST('19000101 ' + work_hour AS DATETIME)))
FROM #temp
)
SELECT CAST(FLOOR(mn / 60) AS VARCHAR(5)) + ':' + CAST(mn % 60 AS VARCHAR(2))
FROM cte
Output:
hm
--------
29:51
Update 2:
DECLARE #temp TABLE
(
transtime_out DATETIME
, transtime_in DATETIME
)
INSERT INTO #temp (transtime_out, transtime_in)
VALUES
('2013-05-19 16:40:53.000', '2013-05-19 08:58:07.000'),
('2013-05-19 16:40:53.000', '2013-05-19 08:58:07.000')
SELECT diff = LEFT(CONVERT(VARCHAR(10), CAST(SUM(CAST(a.transtime_out - a.transtime_in AS FLOAT)) AS DATETIME), 108), 5)
FROM #temp a