Share via

Time diff column as parameter

kasim mohamed 581 Reputation points
2021-03-23T16:54:34.227+00:00

Hi,

I have a table with datetime column like below
80759-image.png

if time is between 1 to 2 then the next column value should be 2.
if time is between 2 to 4 then the next column value should be 4. etc., like below
80629-image.png
how to achieve this in query

Thanks In Advance

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

Viorel 127K Reputation points
2021-03-23T19:11:00.493+00:00

Check this query:

select MyColumn, 
    ((datediff(minute, cast(MyColumn as date), MyColumn) - 1) / (2*60) + 1) * 2 as NextColumn
from @MyTable

And maybe clarify the rules.

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,626 Reputation points
    2021-03-24T05:39:16.983+00:00

    Hi @kasim mohamed ,

    declare @yourtable table(datetimediff char(25))  
    insert into @yourtable values('23/03/2021 0:01'),('23/03/2021 2:00')  
                                ,('23/03/2021 3:00'),('23/03/2021 13:59')  
                                   
    select datetimediff,  
    case when cast(substring(datetimediff,charindex(':',datetimediff)-2,2) as int)%2<>0 then   
    cast(substring(datetimediff,charindex(':',datetimediff)-2,2) as int)+1 else  
    cast(substring(datetimediff,charindex(':',datetimediff)-2,2) as int)+2 end newcolumn  
    from @yourtable  
    

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our [documentation][1] to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.