I m working on sql server and stucked with how can I get the desired output.

I have the below as the source table.

source image

and I want the desired output as below.

Desired Output

Here is the Query to have source table.

   DECLARE @Temp TABLE(Capacity INT,CDate DATE,Name NVARCHAR(100))
   INSERT INTO @Temp VALUES (1,'4/14/2014','M24')
   INSERT INTO @Temp VALUES (1,'4/15/2014','M22')
   INSERT INTO @Temp VALUES (1,'4/14/2014','M24')
   INSERT INTO @Temp VALUES (1,'4/15/2014',NULL)
   INSERT INTO @Temp VALUES (2,'4/14/2014','F67')
   INSERT INTO @Temp VALUES (2,'4/15/2014','F31')
   INSERT INTO @Temp VALUES (3,'4/14/2014','M53')
   SELECT * FROM @Temp

Can anyone help me, please.

有帮助吗?

解决方案

You can use the PIVOT function to get the result but since you need to return multiple rows for each Capacity, you will want to use a windowing function like row_number() that will generate a unique sequence for each Capacity and CDate combination:

SELECT Capacity, [2014-04-14], [2014-04-15]
FROM 
(
  SELECT Capacity, 
    CDate, 
    Name,
    row_number() over(partition by capacity, cdate
                      order by capacity) seq
  FROM @Temp
) d
PIVOT
(
  MAX(name)
  FOR CDate IN ([2014-04-14], [2014-04-15])
) piv
ORDER BY Capacity;

See SQL Fiddle with Demo

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top