-3

I have table with values, described as:

select top(4) Name_Country From DBO.Country
Name_Country
USA
ENGLAND
ITALY
GERMANY

I need values in pivot format as:

NAME_1 NAME_2 NAME_3 NAME_4
USA ENGLAND ITALY GERMANY

Can anyone help on this?

Thanks in advance

Dale K
  • 25,246
  • 15
  • 42
  • 71
amirlol
  • 87
  • 8
  • I tried , but i can't understand about this solution – amirlol Sep 16 '22 at 23:28
  • 1
    then please show us what you tried the highest answer is exactly what you need – nbk Sep 16 '22 at 23:40
  • "When you use TOP with the ORDER BY clause, the result set is limited to the first N number of ordered rows. Otherwise, TOP returns the first N number of rows in an undefined order." (see" [docs for TOP](https://learn.microsoft.com/en-us/sql/t-sql/queries/top-transact-sql?view=sql-server-ver16)) – Luuk Sep 17 '22 at 13:12

2 Answers2

1

You can use a subquery to generate a ROW_NUMBER() using the table insert order (ORDER BY (SELECT 1)), however, you should ORDER BY an actual column in your table. Your table should have a key you can use for this step.

Add more NAME_x row number columns to include more pivoted results:

SELECT 
         MAX(CASE WHEN a.rn = 1 THEN a.Name_Country END) AS NAME_1,
         MAX(CASE WHEN a.rn = 2 THEN a.Name_Country END) AS NAME_2,
         MAX(CASE WHEN a.rn = 3 THEN a.Name_Country END) AS NAME_3,
         MAX(CASE WHEN a.rn = 4 THEN a.Name_Country END) AS NAME_4
    FROM (SELECT b.Name_Country,
                 ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS rn
            FROM Country b) a

Result

NAME_1 NAME_2 NAME_3 NAME_4
USA ENGLAND ITALY GERMANY

Fiddle here.

griv
  • 2,098
  • 2
  • 12
  • 15
1
select [1] as NAME_1
      ,[2] as NAME_2
      ,[3] as NAME_3
      ,[4] as NAME_4
from  (
       select *
              ,row_number() over(order by Name_Country desc) as rn
       from   t
       ) t 
       pivot(max(Name_Country) for rn in([1],[2],[3],[4])) p
NAME_1 NAME_2 NAME_3 NAME_4
USA ITALY GERMANY ENGLAND

Fiddle

DannySlor
  • 4,574
  • 1
  • 3
  • 11