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

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,759 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,555 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.5K 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.


1 additional answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,571 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.

    0 comments No comments