Skip to content
Advertisement

Rounding of hours in sql queries

The values ​​you see below are loaded with a query and they are related to a time stamp. What they ask me to insert is a rounded value; up and down. Rounding must be done at minutes of 15 and 30.

If the round is set to 15 and the marking has been made at 7:59, it is rounded off to 8:00 if the marking is at 8:01 am rounded to 8:15 am, as do I implement this thing within this query?

Query:

select Data, string_agg(Ore, '  ') as Ore 
from ( 
   select FORMAT(DataCreazione, 'dd/MM/yyyy', 'it-IT') as Data,
          CONCAT(DATEPART(HOUR,DataCreazione), ':', DATEPART(MINUTE, DataCreazione)) as
Ore 
   from Marcatura 
    where IdUtente = 2
    and (Stato='Ingresso' or Stato='Uscita') 
     and cast(DataCreazione as DateTime)
        between cast(CONVERT(VARCHAR(10), CONVERT(date, '10-11-18', 5), 23)  as datetime)
            and  cast(CONVERT(VARCHAR(10), CONVERT(date, '10-11-19', 5), 23)  as datetime)
) t 
group by Data 
order by CONVERT(datetime, Data, 105) desc

Values:

 05/07/2019 -- 14:45  19:27
 04/07/2019 -- 11:41  11:41
 07/06/2019 -- 12:39
 01/06/2019 -- 8:27  8:27  8:27  8:27
 18/04/2019 -- 15:41  15:41
 08/04/2019 -- 11:52  11:54
 01/04/2019 -- 7:25
 27/03/2019 -- 21:38  21:38
 23/03/2019 -- 13:32  13:32
 08/03/2019 -- 21:20  21:20
 04/03/2019 -- 21:48  21:48
 02/03/2019 -- 8:3  8:3

If the state is equal to < Ingresso > it is rounded up to the top if the status is < Uscita > is rounded down, for example 07:59 becomes 08:00 whereas if it is 17:44 it becomes 17:45

Advertisement

Answer

The Logic is much more simple than described, perhaps. Try this approach:

EDIT: Applied logic to your own query

select Data, string_agg(Ore, '  ') as Ore 
from ( 
   select FORMAT(DataCreazione, 'dd/MM/yyyy', 'it-IT') as Data,
          CONCAT(
          (Case
              when Datepart(MINUTE, DataCreazione) > 45
              then Datepart(hour, Datacreazione)+1
              else Datepart(hour, Datacreazione)
           end)
           ,':'
           ,(case
                 when DATEPART(MINUTE, DataCreazione) between 0 and 15 then '15'
                 when DATEPART(MINUTE, DataCreazione) between 16 and 30 then '30'
                 when DATEPART(MINUTE, DataCreazione) between 31 and 45 then '45'
                 else '00' end               
            )) as Ore 
   from Marcatura 
    where IdUtente = 2
    and (Stato='Ingresso' or Stato='Uscita') 
     and DataCreazione
    between cast(CONVERT(VARCHAR(10), CONVERT(date, '10-11-18', 5), 23)  as datetime)
            and  cast(CONVERT(VARCHAR(10), CONVERT(date, '10-11-19', 5), 23)  as datetime)
) t 
group by Data 
order by CONVERT(datetime, Data, 105) desc;

SQLFiddle here:

http://sqlfiddle.com/#!18/475202/1
http://sqlfiddle.com/#!18/23d16/13

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement