Tags
Complex SQL Challenges, Complex TSQL Challenge, Interview Qs.SQL SERVER Questions, Interview Questions on SQL, InterviewQuestions, InterviewQuestions for SQL, Learn complex SQL, Learn SQL, Learn T-SQL, PL/SQL Challenges, Puzzles, Queries for SQL Interview, SQL, SQL 2012, SQL 2014, SQL 2014 Interview Questions, SQL Challenge, SQL Challenges, SQL pl/sql puzzles, SQL Puzzles, SQL SERVER Interview questions, SQL SERVER2005/2008, SQL Sudoku, SQLSERVER, T SQL Puzzles, T-SQL Challenge, Tough SQL Challenges, Tough SQL Puzzles, TSQL, TSQL Challenge, TSQL Challenges, TSQL Interview questions, TSQL Queries
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
SELECT [F] AS FemaleCount, [M] As MaleCount
FROM GenderCount
PIVOT (COUNT(Name) FOR Gender IN ([F],[M])) As pvt;
LikeLiked by 1 person