0

I have this table:

F_name ID Type Result
George 1 T-shirt Y
George 1 Pants N
George 2 Boots O
Dani 2 T-shirt Y
Dani 1 Boots Y

I need a SQL server query to merge rows that have the same F_name and ID and transpose columns type and result as follows:

F_name ID T-shirt Pants Boots
George 1 Y N null
George 2 null null O
Dani 2 Y null null
Dani 1 null null Y
Nimantha
  • 6,405
  • 6
  • 28
  • 69
  • It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ](//stackoverflow.com/help/tour) and [How to Ask](//stackoverflow.com/help/how-to-ask). – MEE Feb 22 '18 at 16:42

1 Answers1

0

I think this is the code you need:

SELECT *
FROM mytable
PIVOT
(   MIN([Result]) 
    FOR [Type] IN ([T-Shirt], [Pants], [Boots]) 
)AS p
ORDER BY F_name, ID ASC;

If you want to see it in action, please check this SQL Fiddle.

If you want dynamic columns (T-shit, Pants, Boots), please check this question / answer: SQL Server - Pivot two columns on a 3 column table

Pedro Martins
  • 854
  • 6
  • 9