1

I have a table like below :

    ID   TYPE    VALUE
    1    CC 1     X
    1    CC 2     Y
    1    CC 3    NULL
    1    CC 4    NULL

I am using sql PIVOT and STUFF functionality to get the desired result but still not able to do it. Please if anyone can help me.

Desired Result :

ID [CC 1]  [CC 2]  [CC 3]  [CC 4]
1    X       Y      NULL    NULL
4
  • Are the type values fix? Commented May 22, 2015 at 11:28
  • stackoverflow.com/questions/24470/sql-server-pivot-examples Commented May 22, 2015 at 11:29
  • @juergend may be .. but these are in loop for a particular Id. Let say for Id 1 these are up to 13. then for 2 and so on. Commented May 22, 2015 at 11:37
  • I think you are confusing STUFF with XML concatinate methods. STUFF however doesn't work as you expect. All STUFF does is replace part of a varchar with another part, and when using contatinate is it normallly used to delete the first character Commented May 22, 2015 at 12:35

4 Answers 4

3

You can approach this in several ways. I typically use conditional aggregation:

select id,
       max(case when type = 'CC 1' then value end) as cc1,
       max(case when type = 'CC 2' then value end) as cc2,
       max(case when type = 'CC 3' then value end) as cc3,
       max(case when type = 'CC 4' then value end) as cc4
from <table t>
group by id;
Sign up to request clarification or add additional context in comments.

2 Comments

Can we use stuff or pivot for this.. in other words i want the desired result using stuff or pivot. so please if u can help me..
@vivek . . . The reason I use conditional aggregation is because (1) it works in all databases and (2) it does produce unexpected results due to other columns in the table. I have no idea why this query would require stuff().
0

FULL OUTER JOIN's:

select coalesce(t1.id, t2.id, t3.id, t4.id),
       t1.value as cc1,
       t2.value as cc2,
       t3.value as cc3,
       t4.value as cc4
from (select id, value from tablename where type = 'CC 1') as t1
  full outer join (select id, value from tablename
                   where type = 'CC 2') as t2 ON t1.id = t2.id
  full outer join (select id, value from tablename
                   where type = 'CC 3') as t3 ON t2.id = t3.id
  full outer join (select id, value from tablename
                   where type = 'CC 4') as t  ON t3.id = t4.id

Comments

0

Try the following:

Select id, listagg(value, '-')  within group(order by type) over (partition by id) as txt
From table group by Id, txt

Comments

0

Here is the syntax for pivot;

SELECT ID, [CC 1],[CC 2],[CC 3],[CC 4]
FROM yourtable
PIVOT
(min([value])  
FOR Type
in([CC 1],[CC 2],[CC 3],[CC 4])  
)AS p

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.