DataBase: SQL Fiddle
Query needed: To return the number of women and men of age 25-35 years for each Insurance Company.
My Progress:
CREATE VIEW MenInAge AS
SELECT p.pname,p.pid,p.cid
FROM Patient p
WHERE p.gender = 'm' and p.age between 25 and 35;
CREATE VIEW WomenInAge AS
SELECT p.pname,p.pid,p.cid
FROM Patient p
WHERE p.gender = 'f' and p.age between 25 and 35;
CREATE VIEW MenInAgeCount AS
SELECT m.cid, COUNT(m.pid) as c
FROM MenInAge m
GROUP BY m.cid;
CREATE VIEW WomenInAgeCount AS
SELECT w.cid, COUNT(w.pid) as c
FROM WomenInAge w
GROUP BY w.cid;
How do I show for every InsuranceCompany.cid the WomenInAgeCount.c and the MenInAgeCount.c columns?
Explanation:
You have to join the tables
InsuranceCompaniesandPatientusing the LEFT OUTER JOIN by joining the records oncidcolumn in both tables and also apply the filter to select only patients between age 25 and 35 (including those boundary values). The CASE statement simply checks whether the patient is male or female and computes two different columns by assigning values of 1 if the values match and 0 if the values don’t match. Finally you have to group the result by cname to fetch the count by insurance company name.Explanation about CASE:
In the CASE expression, the query states WHEN gender field value is f assign the column female with the value 1. The value 1 is hard coded because it means the query found 1 row matching the gender=’f’ record and this also represent 1 person. You can also state ELSE 0 but it is implicit so not necessary to specify that. This CASE expression evaluates for every record in the query result. Finanlly, you will get all the rows with female column containing either 1 or 0. When you sum this column female, you will get the total number of females, the same logic goes for male column.
With COALESCE:
COALESCEhere replaces any NULL values with the given value in the second parameter (here in this case zero).Click here to view the demo in SQL Fiddle.
Script:
Output:
Without COALESCE:
Click here to view the demo in SQL Fiddle
Script:
Output: