1

How to do this in sql ?

I have select and the result are :

1 a
2 b
3 c
4 d
5 e

then I want the result to display like

1 2 3 4 5
a b c d e

Thanks Guys!

2
  • 2
    Provide table structure and your select query. Jun 3, 2015 at 6:36
  • 1
    This is generally referred to as a PIVOT. There are plenty of examples both on here of questions and also in the MSDN documentation. Exact details may vary if e.g. there aren't a fixed number of result columns Jun 3, 2015 at 6:40

3 Answers 3

3

You can use pivot

select [1],[2],[3],[4],[5]
from
(
  select column1, column2
  from mytable
) d
pivot
(
  max(column2)
  for column1 in ([1],[2],[3],[4],[5])
) piv;

SQL FIDDLE DEMO

2
  • Column names shouldn't be in [brackets]? Jun 3, 2015 at 6:49
  • @StanislovasKalašnikovas:- I rarerly think that someone will make the column names as 1,2,3.. Anyways updated my code. Although the point was to use PIVOT and the logic. Jun 3, 2015 at 6:50
1

Looks like you need to use pivot statement, https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

-- Potentially your case example:
DECLARE @t TABLE (id int, val CHAR(1));
INSERT INTO @t VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')
-- Pivot table with one row and five columns
SELECT 'Value' AS 'Id', 
        [1], [2], [3], [4], [5]
FROM @t AS SourceTable
PIVOT
(
max(val)
FOR id IN ([1], [2], [3], [4], [5])
) AS PivotTable;
1

You can use PIVOT:

-- Create sample data

CREATE TABLE Test
(
  A INT,
  B NVARCHAR(10)
)
INSERT INTO Test (A, B) VALUES (1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')

-- Pivot query

SELECT [1],[2],[3],[4],[5]
FROM
(
  SELECT A, B
  FROM Test
) x
PIVOT
(
  MIN(B)
  FOR A IN ([1],[2],[3],[4],[5])
) piv;

OUTPUT:

1   2   3   4   5
a   b   c   d   e

SQL FIDDLE

As you asked, dynamic pivot should be like that:

SELECT @cols += ([Name]) + ','
FROM   (
        SELECT  Name
        FROM    Table
        ) a
SET @cols   = LEFT(@cols, LEN(@cols) - 1)
SET @sql    = 
'SELECT * 
 FROM 
    (
    SELECT Col1 as [NamePiv], 
           Col2 as [Val]
    FROM   Table1
    ) x
    PIVOT
    (
        MIN (Val)
        FOR NamePiv IN (' + @cols +') 
    ) p'
1
  • Hi Stanislovavs, thanks for this sample query but what if the column name if dynamic ? the column name are dynamically selected on database table.
    – parpar
    Jun 3, 2015 at 8:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.