Unique results for SQL command with GROUP, MIN and NULL values

北城余情 提交于 2020-01-15 12:15:47

问题


I have a table inquiry with columns job, gender (TRUE for women, FALSE for men) and salary. None of the columns is unique, salary may contain NULL. How to find the minimum salary per job for women (TRUE)? If e.g. there are entries [pilot ; TRUE ; 100], [pilot ; FALSE ; 100], [pilot ; TRUE ; NULL] and [pilot ; FALSE ; 120], the code below returns [pilot ; 100] twice instead of once.

SELECT TOP (100) PERCENT T.JOB, T.SALARY
FROM INQUIRY AS T INNER JOIN
    (SELECT JOB, MIN(SALARY) AS SL
    FROM INQUIRY AS T
    WHERE (SALARY IS NOT NULL) AND (GENDER = 1)
    GROUP BY JOB) AS x ON x.JOB = T.JOB AND x.SL = T.SALARY

回答1:


Aggregate functions ignore nulls. Lose the join and you should be OK:

SELECT   job, MIN(salary)
FROM     inquiry
WHERE    gender = 1
GROUP BY job


来源:https://stackoverflow.com/questions/47352218/unique-results-for-sql-command-with-group-min-and-null-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!