I have query which returns clients loans with associated collateral names like below (1) but I want to have only one distinct loan number in a row and collateral names aside like on other example (2). Been playing with pivoting but cannot figure it out because I don't have aggregate column and I don't know how many loan numbers I will get neither how many collateral each loan may have. How to do that??? Possible in SQL Server 2012?
thanks
(1)
loanid|name |Address |
1 |John |New York|
1 |Carl |New York|
1 |Henry |Boston |
2 |Robert|Chicago |
3 |Joanne|LA |
3 |Chris |LA |
(2) I need something like this
loanid|name |address |name |address |name|address|
1 |Jonh |New York |Carl |New York|Henry|Boston|
2 |Robert|Chicago |
3 |Joanne|LA |Chris|LA|
While M.Ali's answer will get you the result, since you are using SQL Server 2012 I would unpivot the
name
andaddress
columns slightly different to get the final result.Since you are using SQL Server 2012, you can use
CROSS APPLY
withVALUES
to unpivot these multiple columns into multiple rows. But before you do that, I would userow_number()
to get the total number of new columns you will have.The code to "UNPIVOT" the data using CROSS APPLY looks like:
See SQL Fiddle with Demo. This is going to get your data into a format similar to:
You now have a single column
COL
with all of your new column names and the values associated are also in a single column. The new column names now have a number at the end (1, 2, 3, etc) based on how many total entries you have perloanid
. Now you can apply PIVOT:See SQL Fiddle with Demo. Finally if you don't know how many pairs of
Name
andAddress
you will have then you can use dynamic SQL:See SQL Fiddle with Demo. Both versions give a result:
This would put
Test Data
Query
Result Set
Update for Dynamic Columns
Note
This wouldnt work with the given sample data in my answer, as it uses a table variable and it is not visible to dynamic sql since it has it own scope. but this solution will work on a normal sql server table.
Also the order in which columns are selected will be slightly different.