Share via

Query for multiple rows

Anonymous
2020-09-23T03:10:03.657+00:00

Hello,
I've a table data as shown below.

DECLARE @prod TABLE (id int, abr int, ubr int)
INSERT INTO @prod
VALUES
(1 , 1 , 0),
(1 , 0 , 1),
(2 , 0 , 1),
(2 , 1 , 0)
select * from @prod

For - ID, I've abr value in one row. UBR value in another row.
I want both values in one row.
I want results as shown below:

id abr ubr
1 1 1
2 1 1

Can you please help me with this.

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.

0 comments No comments

Answer accepted by question author

Tom Cooper 8,501 Reputation points
2020-09-23T03:21:52.033+00:00

Assuming the value you want is the one which is not equal to 0, then

Select id,
  Max(Case When abr <> 0 Then abr Else Null End) As abr,
  Max(Case When ubr <> 0 Then ubr Else Null End) As ubr
From @prod
Group By id
Order By id;

Tom

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,626 Reputation points
    2020-09-23T03:20:23.207+00:00

    Hi @VaralaxmiPandikonda-4750,

    Please refer to:

    DECLARE @prod TABLE (id int, abr int, ubr int)  
    INSERT INTO @prod  
    VALUES  
    (1 , 1 , 0),  
    (1 , 0 , 1),  
    (2 , 0 , 1),  
    (2 , 1 , 0)   
    ;with cte  
    as(select id,case when abr=0 then ubr else abr end abr,case when ubr=0 then abr else ubr end ubr,  
    row_number() over(partition by id order by id)rn   
    from @prod)  
      
    select id,abr,ubr from cte   
    where rn<2  
    

    26585-image.png

    If you have any question, please feel free to let me know.
    If the response is helpful, please click "Accept Answer" and upvote it.

    Best Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation 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.