SQL Query, possible to do in one query?
I need to write a query that does the following:
I have two tables:
SalaryRanges: id, beginRange, endRange
UserInfo: id, salary,...
I would like to have a query that does the following:
Give me a list of ids开发者_运维百科 of SalaryRanges where there are more than 5 persons meeting that specific range for each salary range.
So something like:
SalaryRange ids: 1, 4, 5, 7 have 5+ people meeting their respective salary ranges.
Is this possible to do in one query? Or do you need to break the query up into different calls?
This is just from the top of my head but I think it would work
SELECT sr.id
FROM SalaryRanges AS sr
INNER JOIN UserInfo AS ui ON ui.Salary >= sr.beginRange AND ui.Salary <= sr.endRange
GROUP BY sr.id
HAVING count(ui.id) > 5
Ok the updated version using BETWEEN as per the comment
SELECT sr.id
FROM SalaryRanges AS sr
INNER JOIN UserInfo AS ui ON ui.Salary BETWEEN sr.beginRange AND sr.endRange
GROUP BY sr.id
HAVING count(ui.id) > 5
Both should work though
精彩评论