t-sql question

Sri Kotte 21 Reputation points
2021-09-02T00:56:58.607+00:00

Hello all,

I am trying pivoting my query

I have a table with below columns

div_id primo md curve_name curve_value

10 1234 12 rop 45.6
10 1234 13 rop 43.5
10 1234 14 rop 40.6
10 1234 12 hook_load 11.2
10 1234 13 hook_load 12.3

I am trying to get the output like this

div_id primo md rop hook_load
10 1234 12 45.6 11.2
10 1234 13 43.5 12.3
10 1234 14 40.6 null

I am trying like this

SELECT *
FROM (SELECT *
FROM table123
WHERE primo = 1234
AND curve_name IN ('ROP',
'HOOK_LOAD')
)
PIVOT (MAX (curve_value)
FOR (curve_name)
IN ('ROP' AS rop,
'HOOK_LOAD' AS HOOK_LOAD))

I am getting the output as

div_id primo md rop hook_load

10 1234 12 45.6
10 1234 12 11.2
10 1234 13 43.5
10 1234 13 12.3

bottomline is my md is repeating..Could you please help where I am doing it wrong?

Thanks for the help

Developer technologies | Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. EchoLiu-MSFT 14,621 Reputation points
    2021-09-02T01:18:22.31+00:00

    Hi @Sri Kotte ,

    Please try:

    CREATE TABLE #test(div_id int,primo int,md int,curve_name varchar(25),curve_value decimal(3,1))  
    INSERT INTO #test VALUES(10,1234,12,'rop',45.6),  
    (10,1234,13,'rop',43.5),  
    (10,1234,14,'rop',40.6),  
    (10,1234,12,'hook_load',11.2),  
    (10,1234,13,'hook_load',12.3)  
      
    SELECT *  
    FROM (SELECT div_id,primo,md,curve_name,curve_value   
    FROM #test  
    WHERE primo = 1234  
    AND curve_name IN ('ROP',  
    'HOOK_LOAD')  
    ) t  
    PIVOT (MAX (curve_value)  
    FOR curve_name  
    IN (ROP,HOOK_LOAD)) p  
    

    Output:
    128389-image.png

    For more details, please refer to::
    FROM - Using PIVOT and UNPIVOT

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

    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.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Sri Kotte 21 Reputation points
    2021-09-02T01:51:53.56+00:00

    That worked.Thank you so much :)

    0 comments No comments

Your answer

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