Since PIVOT requires aggregation, your current query will only return the min/max value of each DisposalId
. In order to get the result that you want you have to create column that will be used as your new column headers.
I would use row_number()
and partition the data by your ReportId
. The subquery that you are using would be altered slightly to the following:
SELECT [DisposalID]
,[ReportID]
, 'DisposalId'
+cast(row_number() over(partition by reportId
order by disposalid) as varchar(10)) seq
FROM [dbo].[DisposalConsolidatedView]
WHERE [ReportID]=84
See SQL Fiddle with Demo. This is going to create a column with the values DisposalId1
and DisposalId2
- these new values will be your new column headers and then you will apply the aggregate to your existing DisposalId
column.
The final syntax will be:
select DisposalId1, DisposalId2, ReportId
from
(
SELECT [DisposalID]
,[ReportID]
, 'DisposalId'
+cast(row_number() over(partition by reportId
order by disposalid) as varchar(10)) seq
FROM [dbo].[DisposalConsolidatedView]
WHERE [ReportID]=84
) DataTable
PIVOT
(
Min(disposalid)
FOR seq IN (DisposalId1, DisposalId2)
) PivotTable;
See SQL Fiddle with Demo. This will give a result:
| DISPOSALID1 | DISPOSALID2 | REPORTID |
|-------------|-------------|----------|
| 242 | 243 | 84 |