-1

I have a table (table1) containing:

Sub_county_name, county_name, malepop(for each sub county), femalepop(for each sub county)

I want to make a report that gives me the sub counties with the highest male and highest female population in their county.

What I've tried:

I have created two queries,one for calculating sub county with highest male pop and one for calculating sub county with highest female pop. However, I am not sure how to combine the two into a single report. Could I get a hint on how to do that?

The queries I have used are:

SELECT Sub_county_name,county_name,male_pop
FROM table1
WHERE male_pop = (SELECT MAX(male_pop) FROM table1 a
                  WHERE a.county_name = table1.county_name);


SELECT Sub_county_name,county_name,female_pop
FROM table1
WHERE female_pop = (SELECT MAX(female_pop) FROM table1 a
                    WHERE a.county_name = table1.county_name);
1
  • OR the two WHERE clauses together?
    – jarlh
    Nov 17, 2015 at 11:02

2 Answers 2

0

If you need to combine the queries , you can get using following query :

SELECT        Sub_county_name, county_name, male_pop, female_pop
FROM            table1
WHERE        (male_pop =
                             (SELECT        MAX(male_pop) AS Expr1
                               FROM            table1 AS a
                               WHERE        (county_name = table1.county_name))) AND (female_pop =
                             (SELECT        MAX(female_pop) AS Expr1
                               FROM            table1 AS a
                               WHERE        (county_name = table1.county_name)))
1
  • I guess OP wants OR instead of AND.
    – jarlh
    Nov 17, 2015 at 11:19
0

I would suggest putting the subqueries into the FROM clause:

SELECT table1.*
FROM table1 JOIN
     (SELECT county_name, MAX(male_pop) as maxmp, MAX(female_pop) as maxfp
      FROM table1
      GROUP BY county_name
     ) m
     ON table1.county_name = m.county_name and
        (table1.male_pop = m.maxmp OR table1.female_pop = m.maxfp);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.