Daniel
Daniel

Reputation: 9839

TSQL transpose rows to columns based on fixed set of input values

I want to transpose a table based on a limited number of input values for column Brand

My source:

Id Brand Type
1 Adidas Type A
1 Puma Type B
2 Adidas Type C
2 Puma Type D

Desired Output:

Id Brand Adidas Type Adidas Brand Puma Type Puma
1 Adidas Type A Puma Type B
2 Adidas Type C Puma Type D

I am pretty sure this can be done using the Pivot function but i have no clue how.

Upvotes: 0

Views: 25

Answers (1)

Daniel
Daniel

Reputation: 9839

Hm. Found out by myself without using a PIVOT function.

SELECT
    Id,
    MAX(CASE WHEN Brand = 'Adidas' THEN [Brand] END) AS [Brand Adidas], 
    MAX(CASE WHEN Brand = 'Adidas' THEN [Type] END) AS [Type Adidas],
    MAX(CASE WHEN Brand = 'Puma' THEN [Series] END) AS [Brand Puma],
    MAX(CASE WHEN Brand = 'Puma' THEN [Type] END) AS [Type Puma]
FROM MyTable
GROUP BY Id

Output:

Id Brand Adidas Type Adidas Brand Puma Type Puma
1 Adidas Type A Puma Type B
2 Adidas Type C Puma Type D

Upvotes: 1

Related Questions