Click here to Skip to main content
11,721,671 members (68,664 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: ASP.NET MySQL query
I have this table

ID         gender       companyName
1             M         Company A
2             M         Company A
3             F         Company A
4             F         Company B

I want this result:


CompanyName          M           MPercent    F     FPercent
Company A            2              66       1       33
Company B            0              0        1      100

*MPercent for Company A is 2/3 = 66%, FPercent is 1/3 = 33%.
*MPercent for Company B is 0/1 = 0%, FPercent is 1/1 = 100%.

Possible to get the result by using mysql query only?
Posted 27-Nov-12 22:03pm
melvintcs1.1K
Edited 27-Nov-12 22:04pm
v2
Comments
Krunal R at 28-Nov-12 4:05am
   
What have you tried ??

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

This will do it:

SELECT	[companyName],
	SUM(CASE WHEN gender='M' THEN 1 ELSE 0 END) AS M,
	(SUM(CASE WHEN gender='M' THEN 1 ELSE 0 END)*100)/COUNT(*) AS MPercent,
	SUM(CASE WHEN gender='F' THEN 1 ELSE 0 END) AS F,
	(SUM(CASE WHEN gender='F' THEN 1 ELSE 0 END)*100)/COUNT(*) AS MPercent
FROM	[tempdb].[dbo].[companyTable]
GROUP BY companyName  

In response to your comment, you simply need to put a seperate query within the select clause:

SELECT  [companyName],
    SUM(CASE WHEN gender='M' THEN 1 ELSE 0 END) AS M,
    (SUM(CASE WHEN gender='M' THEN 1 ELSE 0 END)*100)/COUNT(*) AS MPercent,
    (SUM(CASE WHEN gender='M' THEN 1 ELSE 0 END)*100)/(SELECT COUNT(*) FROM companyTable) AS MTotalPercent,
    SUM(CASE WHEN gender='F' THEN 1 ELSE 0 END) AS F,
    (SUM(CASE WHEN gender='F' THEN 1 ELSE 0 END)*100)/COUNT(*) AS FPercent,
    (SUM(CASE WHEN gender='F' THEN 1 ELSE 0 END)*100)/(SELECT COUNT(*) FROM companyTable) AS FTotalPercent,
FROM    companyTable
GROUP BY companyName
  Permalink  
v2
Comments
melvintcs at 28-Nov-12 21:48pm
   
What should i do if i need to add a new percent, which is record/total record:

1. for company A, 3/4 = 75%
2. for company B, 1/4 = 25%

i tried, but i cant get the '4' since there is a GROUP BY inside the query. COUNT(*) give me result of '3' for company A

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 435
1 OriginalGriff 269
2 Mika Wendelius 170
3 cyycoish 70
4 ppolymorphe 66
0 Sergey Alexandrovich Kryukov 2,249
1 OriginalGriff 1,024
2 F-ES Sitecore 690
3 Maciej Los 619
4 Richard MacCutchan 580


Advertise | Privacy | Mobile
Web02 | 2.8.150901.1 | Last Updated 28 Nov 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100