Learn From - Interactive SQL



Case statement and SUBQUERY.


Used SUBQUERY and Case statement to split a Column into two.
Below is shown the "ProfileInfo" table:

PersonName PersonsSex DateOfBirth MaritalStatus
Elizabeth Brown Female 5/12/1984 12:00:00 AM Married
Hanna Moos Female 2/17/1990 12:00:00 AM Single
Hari Kumar Male 1/29/1984 12:00:00 AM Single
Howard Snyder Male 3/27/1991 12:00:00 AM Single
Patricio Simpson Male 7/24/1984 12:00:00 AM Married
Peter Franken Male 3/22/1987 12:00:00 AM Single
Thomas Hardy Male 9/11/1984 12:00:00 AM Married
Yang Wang Female 2/11/1987 12:00:00 AM Single

SQL using Case statement and SUBQUERY



In the "ProfileInfo" table the People Profiles Information is listed

In the SQL Query the DATEDIFF function is used to get the Age.

Here in the "ProfileInfo" table, the column PersonsSex contains only two values "Male" and "Female". Using the Case statement we can split the PersonsSex column into "MaleCount" and "FemaleCount" columns.

Text Editor below has the SQL Query, click the "View Result" button, to see the result.

Select DATEDIFF(yyyy, DateOfBirth, GETDATE()) as Age ,
(Case When PersonsSex = 'Male' then 1 else 0 End) as MaleCount,
(Case When PersonsSex = 'Female' then 1 else 0 End) as FemaleCount
From ProfileInfo;

Note: The PersonsSex column is now split as "MaleCount" and "FemaleCount" columns.

Above Query Executed Result:
Age MaleCount FemaleCount
40 0 1
34 0 1
40 1 0
33 1 0
40 1 0
37 1 0
40 1 0
37 0 1


In the query shown below, the above query is used as a Table with alias "tbl" in the From clause.

SQL Query to know how many males and females are born in an age group.

Select tbl.Age,
SUM(tbl.MaleCount) as MaleCount,
SUM(tbl.FemaleCount) as FemaleCount,
(SUM(tbl.MaleCount) + SUM(tbl.FemaleCount)) as TotalCount
From
(
     Select DATEDIFF(yyyy, DateOfBirth, GETDATE()) as Age ,
     (Case When PersonsSex = 'Male' then 1 else 0 End) as MaleCount,
     (Case When PersonsSex = 'Female' then 1 else 0 End) as FemaleCount
     From ProfileInfo
)as tbl
Group By tbl.Age;

Note: The from Clause uses the SUBQUERY that acts as a table with the alias name "tbl". In the SUBQUERY Case Statements are used to seperate the MaleCount and FemaleCount. Later the GROUP BY is used to get the sum of MaleCount and FemaleCount.

SQL in Text Editor: