开发者

SQl SELECT Percentage

have two three tables one for student, second for class, and the third for gender. I am trying to get the total number of each gender and the percentage. I used the following statment to get the number and it works well:

SELECT Gender.GenderName as Gender, COUNT(*) as cnt  
FROM         (Client INNER JOIN
             Gender ON Student.GenderID = Gender.GenderID)
             GROUP BY Gender.GenderName

I could not figure out 开发者_JAVA技巧how I can get the percenage, also how to make ClassName or ID as as selectable item to get the gender for each class or all classes by using @ClassId int.


I don't have access to a SQL Server right now but you use either Cast or Convert to convert to a floating type. Or you may want to refer to your SQL Server's documentation for its specific type conversion functions.

SELECT a.Gender, a.cnt, Cast(a.cnt as float) / b.cnt * 100
  FROM (SELECT Gender.GenderName as Gender, COUNT(*) as cnt
          FROM Client 
    INNER JOIN Gender 
           ON Student.GenderID = Gender.GenderID 
      GROUP BY Gender.GenderName) a
    CROSS JOIN (SELECT COUNT(*) as cnt FROM student) b

PS: Thanks for pointing out my mistake. a.cnt/b.cnt would do integer math and return zero if b.cnt > a.cnt (In this case it would be) ... we need to convert either a.cnt or b.cnt to a float so a.cnt/b.cnt becomes a float and then times it by 100 to give you the percent. Also, I missed that the GenderName had been aliased in the inner SELECT.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜