Solved

Count Where Sex = 'Male' .... ?

Posted on 2004-08-18
4
1,228 Views
Last Modified: 2011-10-03
Im trying to do a count on an employee sex in a view

I have the following table (example)

Department          Sex
IT                         M
IT                         F
IT                         M
Other                    F
Other                    M
Other                    F

i want the results as follows (example)

Department    Female        Male          
IT                   1                 2
Other              2                 1
0
Comment
Question by:Y2Kingswood
  • 2
4 Comments
 
LVL 15

Expert Comment

by:jdlambert1
Comment Utility
Try this:

SELECT sub1.Department, Female, Male
FROM
(SELECT Distinct Department FROM TableA) sub1
 LEFT JOIN (SELECT Department, Count(*) as Female
    FROM TableA
    WHERE Sex = 'F'
    GROUP BY Department
) sub2 ON sub1.Department = sub2.Department
 LEFT JOIN (SELECT Department, Count(*) as Male
    FROM TableA
    WHERE Sex = 'M'
    GROUP BY Department
) sub3 ON sub1.Department = sub3.Department
ORDER BY sub1.Department
0
 
LVL 10

Accepted Solution

by:
AaronAbend earned 50 total points
Comment Utility
select department, sum(case sex when 'F' then 1 else 0 end) as feMale , sum(case sex when 'M' then 1 else 0 end) as Male
group by department
0
 
LVL 15

Expert Comment

by:jdlambert1
Comment Utility
Y2Kingswood, not only is AaronAbend's query shorter, it runs much faster than mine, too.
0
 

Author Comment

by:Y2Kingswood
Comment Utility
i have tried both and you are right, im happy to split the points or give them all to Aaron, let me know what you think is fair
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now