Your request seems very simple, but it has two difficulties. First, one line is a summary of the other two. This involves using rollup or grouping sets in the request.
The second requirement is to make a difference, even if you have no data. This involves using the driver subquery. Such a subquery defines all rows in the output before assigning values. You are using a driver table with left outer join .
An undefined requirement may be the mention of only one year.
The following query approach puts the final form together throughout the year. Then the left connects the summary, pulling the values from there, if any:
with year as ( select 2013 as Year ) select driver.label, coalesce(s.value, 0) as Value, driver.Year from ((select 'Male' as label, year from year ) union all (select 'Female' as label, year from year ) union all (select 'Total' as label, year from year ) ) driver left outer join (select coalesce(Gender, 'Total') as Gender, year.year, count(*) as value from Students cross join year group by Gender with Rollup ) s on driver.year = s.year;
This assumes that the gender is represented as “male” and “female”, and that the data has a column named year (without entering samples or table formats, you need to guess the column names and sample values).
Gordon linoff
source share