0

I have the following table :

Team Department1 Department2 Department3
1    Marketing   Sales       Finance
2    Sales       IT          HR

I want to transpose data like below :

Team Marketing Sales  Finance IT HR
1    1         1      1       0  0
2    0         1      0       1  1

3 Answers 3

2

You can use case logic:

select team,
       (case when 'Marketing' in (Department1, Department2, Department3) then 1 else 0
        end) as marketing,
       (case when 'Sales' in (Department1, Department2, Department3) then 1 else 0
        end) as sales,
       (case when 'Finance' in (Department1, Department2, Department3) then 1 else 0
        end) as finance,
       (case when 'IT' in (Department1, Department2, Department3) then 1 else 0
        end) as it,
       (case when 'HR' in (Department1, Department2, Department3) then 1 else 0
        end) as hr
from t;
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT Team,
       (CASE WHEN 'Marketing' IN (Department1, Department2, Department3) THEN 1 else 0
        end) AS Marketing
...
FROM yourtable;

Comments

1

Unpivot your table first, then it's pretty simple conditional aggregation.

select team,
       count(case when v.Department = 'Marketing' then 1 end) as marketing,
       count(case when v.Department = 'Sales' then 1 end) as sales,
       count(case when v.Department = 'Finance' then 1 end) as finance,
       count(case when v.Department = 'IT' then 1 end) as it,
       count(case when v.Department = 'HR' then 1 end) as hr
from t
cross apply (
    (Department1),
    (Department2),
    (Department3)
) v(Department)
group by team;

You table design is faulty. You should have TeamDepartment as a separate many-to-many linking table

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.