-3

I have a view vw_Country which returns the following records:

enter image description here

I want to write a query using this view to return following results:

enter image description here

Any help would be appreciated!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mandar Patil
  • 538
  • 2
  • 10
  • 29
  • 5
    Possible duplicate of [Convert Rows to columns using 'Pivot' in SQL Server](https://stackoverflow.com/questions/15931607/convert-rows-to-columns-using-pivot-in-sql-server) – e_i_pi Mar 29 '18 at 02:20
  • Thanks for sharing link. But I don't have any column to perform aggregate on. – Mandar Patil Mar 29 '18 at 02:51

2 Answers2

1

Without a column to pivot on, it isn't possible, but you can create a column to pivot on. Something like this should probably work:

SELECT Rownum, [Australia], [India], [United States]
FROM 
    (SELECT ROW_NUMBER() OVER(PARTITION BY Country, ORDER BY City) AS Rownum, Country, City
        FROM vw_Country
        ) sourcetable
    PIVOT 
        (
        MIN(City)
        FOR Country IN ([Australia], [India], [United States])
        ) AS pvt
ORDER BY pvt.Rownum
Katerine459
  • 465
  • 1
  • 3
  • 13
0

Create another column by using rank then use pivot.

Select [Australia], [India], [United States]
from 
(
  select Country, City, 
   Rank() over (partition by country order by city) as rnk
  from yourTable
) src
 pivot
(
 Max(City)
  for Country in ([Australia], [India], [United States])
) piv;
jose_bacoy
  • 12,227
  • 1
  • 20
  • 38