Reputation: 181
I have one table name called tblOperation. I would like to get the output row to column.
E.g:
SNO Operation
---------------------
1 OP10
2 OP20
3 OP20
. .
. .
N N
I need below output format:
OP10 OP20 OP30.....N
How to do it.
Please help me to solve this query.
Upvotes: 2
Views: 559
Reputation: 122
The syntax of pivot operator like this :
SELECT <non-pivoted column>,
[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
[last pivoted column] AS <column name>
FROM
(<SELECT query that produces the data>)
AS <alias for the source query>
PIVOT
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;
Upvotes: 0
Reputation: 15977
Better use dynamic SQL in that case:
DECLARE @sql nvarchar(max),
@cols nvarchar(max)
SELECT @cols = STUFF((
SELECT DISTINCT ','+QUOTENAME(Operation)
FROM tblOperation
FOR XML PATH('')),1,1,'')
SELECT @sql = '
SELECT *
FROM tblOperation
PIVOT(
MAX(sno) FOR Operation IN ('+@cols+')
) AS pvt'
EXEC sp_executesql @sql
Upvotes: 1
Reputation: 322
SELECT *
FROM piovoit
PIVOT(max(sno)
FOR opration IN ([OP10],[OP20],[OP30])) AS PVTTable
Upvotes: 1