Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
but gender male and female count is displayed rowise but classes in column.

What I have tried:

select * from (select CAST(dateOfadmission AS DATE) Date,WardNo,gender,1 AS CntCol from ipd group by gender,dateOfAdmission,wardNo) as tr PIVOT(count(CntCol) for wardNo in ([class ii],[class 2],[class 3],[class iv],[class 5] where Month(CONVERT(smalldatetime,Date,103))=4 order by Date
Posted
Updated 29-May-16 7:33am
Comments
CHill60 2-May-16 13:47pm    
Provide some sample data and your expected results
CHill60 29-May-16 13:04pm    
If you still need some assistance with this please post some sample data and an expected result

1 solution

You only need a few minor changes to your query. Instead of
SQL
1 AS CntCol
use
SQL
COUNT(*) AS CntCol

There is a bug in your SQL, some missing brackets and you need to give the sub-query an alias e.g.
SQL
...,[class 5] where Month...
should be
...,[class 5])) as src where Month...

The derived column Date is already a DATE so there is no need for the conversion in the Where clause. Also if you use SQL reserved words as column names you should surround them with [ ] i.e.
SQL
Month(CONVERT(smalldatetime,Date,103))
becomes
SQL
Month([Date])

I created some sample data on what I guessed were your table structures and with this query
SQL
select * from (
	select CAST(dateOfadmission AS DATE) [Date],
		WardNo,gender, count(*) as CntCol
		from ipd 
		group by gender,dateOfAdmission,wardNo
) as tr 
PIVOT(sum(CntCol) for wardNo in ([class ii],[class 2],[class 3],[class iv],[class 5])) as src
where Month([Date])=4 order by Date
I got results that look like
Date            Gender   class ii class 2 class 3 class iv class5
2016-04-01	F	 3	  2	  3	  2	   5
2016-04-01	M	 4	  4	  4	  4	   2
2016-04-02	F	 3	  2	  3	  2	   5
2016-04-02	M	 4	  4	  4	  4	   2
 
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