0

In a SQL Server how to change column data's as a row wise format?...

For ex:

Input

Name   date
--------------
xxx    12/12/2015
xxx    11/12/2015
xxx    10/12/2015
yyy    9/12/2015

Desired output:

Name  Date
------------------------------------------
xxx   10/12/2015  11/12/2015  12/12/2015
yyy   9/12/2015
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

Check this:

DECLARE @DataSource TABLE
(
    [name] CHAR(3)
   ,[date] DATE
);

INSERT INTO @DataSource ([name], [date])
VALUES ('xxx', '12/12/2015')
      ,('xxx', '11/12/2015')
      ,('xxx', '10/12/2015')
      ,('yyy', '9/12/2015');

WITH DataSource AS
(
    SELECT DISTINCT [name]
    FROM @DataSource
)
SELECT [name]
      ,STUFF
       (
            (
                SELECT ' ' + CAST([date] AS VARCHAR(12)) 
                FROM @DataSource
                WHERE DS.[name] = [name]
                ORDER BY [date] ASC
                FOR XML PATH(''), TYPE
            ).value('.', 'VARCHAR(MAX)')
            ,1
            ,1
            ,''
        )
FROM DataSource DS;

enter image description here

gotqn
  • 42,737
  • 46
  • 157
  • 243
  • Gotgn yes we got result from your query thank you very much for response..., but we have table in DB so need to declare table, how to retrieve result from directly from table with select query statement – Ethirajram Jun 15 '15 at 13:39
  • You can check this link - http://www.sql-server-helper.com/tips/date-formats.aspx in order to represent the date in different format. – gotqn Jun 15 '15 at 13:40
  • @Ethirajram Do not declare new table, just replace the `@DataSource` with your real table name in the `WITH` clause and it will be fine. – gotqn Jun 15 '15 at 13:47
  • yes Gotgn thank you.., – Ethirajram Jun 15 '15 at 13:50