Tags

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,


T-SQL Query | [ Male and Female Count Puzzle ]  – In this puzzle we have to count males and females from the input table. Please check out the sample input and expected output for details.

Sample Input

NAME Gender
Pawan M
Isha F
Neeraj M
Mayank M
Sandeep M
Gopal M
Sugandha F
Kritika F

Expected Output

FemaleCount MaleCount
3 5

Rules/Restrictions

  • The solution should be should use “SELECT” statement or “CTE”.
  • Add your solution(s) in the comments section or send you solution(s) to pawankkmr@gmail.com

Script

Use the below script to generate the source table and fill them up with the sample data.

 


--Create Table

CREATE TABLE GenderCount
(
NAME VARCHAR(10)
,Gender VARCHAR(1)
)
GO

--INSERT Data
INSERT INTO GenderCount(NAME,Gender)
VALUES
('Pawan','M'),
('Isha','F'),
('Neeraj','M'),
('Mayank','M'),
('Sandeep','M'),
('Gopal','M'),
('Sugandha','F'),
('Kritika','F')

--Verify Data
SELECT NAME,Gender FROM GenderCount

UPDATE – 24-Apr-2015 – Solution 1


--

SELECT 
	 SUM(CASE WHEN Gender = 'F' THEN 1 ELSE 0 END ) FemaleCount
	,SUM(CASE WHEN Gender = 'M' THEN 1 ELSE 0 END ) MaleCount	
FROM GenderCount
`
--

Add a comment if you have any other solution in mind. We all need to learn.

Keep Learning

http://MSBISkills.com

Advertisements