Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,

i have a table result for a sql
SQL
SELECT SempMstrSdeptId as DeptId, COUNT(*) AS "Nos"
FROM SgEmployeeMaster
GROUP BY SempMstrSdeptId


as below

DeptId   Nos
------  ---
 1       4
 11      5
 5       10


But i want the result table as below.

1   11   5
--  --   --
4    5   10


then, how to get the above table.what is the change in sql?

Thanks..
Posted
Updated 22-Jan-14 0:17am
v2

Classic pivot.
Assuming that you're using SqlServer you have a description on how to use it here[^].

If you have another database you'll have to update your question accordingly.
 
Share this answer
 
Please use the below example

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' +
QUOTENAME(Replace(SempMstrSdeptId,char(CAST(0x0016 as int)),'')) val
FROM temp
ORDER BY val asc
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
PRINT @cols

SELECT @query =

'SELECT
' + @cols + '
FROM (
Select
SempMstrSdeptId AS DeptId
From
temp
) t
PIVOT
(
Sum(DeptId)
FOR DeptId IN( ' + @cols + ' )' +
' ) AS p; ';


Execute(@query);

Sample Output:

1 4
-- --
3 8
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900