1. Using SEC_TO_TIME, TIME_TO_SEC seems like overkill. Why not just use
TIMESTAMPDIFF[
^]
2. You have a poor db design - there is no need to repeat the workers forename and surname in the
leave
table - you have that information on the
workers
table and you have a link to that table in
leave.ID_WORKER
3. I can't see any reason for all of those sub-queries (and it wouldn't compile for me) Something like the following is far simpler, and easier to follow
select W.fname, W.lname, NUMBER_ORDER, DESC_ORDER
,SUM(TIMESTAMPDIFF(HOUR, os.begin_date, os.end_date)) as hoursWorkedOnOrders
,SUM(TIMESTAMPDIFF(HOUR, l.BEGIN_DATE, L.END_DATE)) as leavetime
,SUM(TIMESTAMPDIFF(HOUR, os.begin_date, os.end_date)) + SUM(TIMESTAMPDIFF(HOUR, l.BEGIN_DATE, L.END_DATE)) as totaltime
from #workers W
INNER JOIN #order_status OS ON W.id_worker = OS.id_worker
INNER JOIN #orders O ON OS.id_order = O.id_order
LEFT OUTER JOIN #leave L ON L.id_worker = W.id_worker
GROUP BY W.fname, W.lname, NUMBER_ORDER, DESC_ORDER
Edit - as an aside, I commend you for providing your table schemas, sample data, attempted code and expected results which is why I am upvoting your question. If you want to make it even easier for us to help you, avoid drawing tables with your data and just give us some simple ddl to reproduce the problem. To explain what I mean here is the sample data I used to get the above solution:
create table #leave(ID_LEAVE int identity(1,1),ID_WORKER int, FNAME varchar(30), LNAME varchar(30), BEGIN_DATE datetime, END_DATE datetime)
insert into #leave(ID_WORKER, FNAME, LNAME, BEGIN_DATE, END_DATE) values
(1, 'DAVID', 'BUCS','2019-03-19 07:00:00','2019-03-19 15:00:00'),
(2, 'MARK', 'GREEN','2019-03-21 07:00:00','2019-03-21 15:00:00')
select * from
create table #workers(ID_WORKER int identity(1,1), FNAME varchar(30) , LNAME varchar(30))
insert into #workers (FNAME , LNAME) values
('DAVID', 'BUCS'),
('MARK', 'GREEN')
create table #orders (ID_ORDER int, DESC_ORDER varchar(30), NUMBER_ORDER varchar(30))
insert into #orders (ID_ORDER , DESC_ORDER , NUMBER_ORDER) values
(20, 'TEST', 'TEST')
create table #order_status(Id_status int identity(30,1),ID_WORKER int, ID_ORDER int, BEGIN_DATE datetime, END_DATE datetime, ORDER_DONE varchar(3))
insert into #order_status (ID_WORKER, ID_ORDER, BEGIN_DATE, END_DATE, ORDER_DONE) values
(1, 20 ,'2019-03-18 06:50:35' ,'2019-03-18 15:21:32', 'NO' ) ,
(1, 20 ,'2019-03-20 06:44:12' ,'2019-03-20 15:11:23', 'NO' ) ,
(1, 20 ,'2019-03-22 06:50:20' ,'2019-03-22 12:22:33', 'YES' ) ,
(2, 20 ,'2019-03-18 06:45:11' ,'2019-03-18 15:14:45', 'NO' ) ,
(2, 20 ,'2019-03-20 06:50:22' ,'2019-03-20 15:10:32', 'NO' ) ,
(2, 20 ,'2019-03-22 06:54:11' ,'2019-03-22 11:23:45', 'YES' )