SQL组返回错误的结果

时间:2019-10-09 16:52:34

标签: mysql sql group-by

我有一个薪水表,我试图在该表中返回确定最低工资,并确定每年行业获得正确的最低薪水我收到了错误的行业名称。

我知道这是由于我使用GROUP BY而不在其上施加任何约束(?)所致,因此它返回的值是错误的,但我不确定如何解决。

工资表

  • salaryID
  • salaryAmount
  • salaryYear
  • industryName(ForeignKey)

有人可以引导我走正确的路吗?

    **(Problem Code)**
    SELECT MIN(S.salary), S.industryName, S.salaryYear
    FROM salary
    GROUP BY S.salaryYear;



    **(Attempted solution)**
    SELECT S.salary
    FROM salary
    INNER JOIN 
    SELECT (min(S1.amount)), S1.year, S1.industryName, S1.salaryId 
    FROM salary S1 
    GROUP BY S1.year
    ON S.salaryId = S1.salaryId);

2 个答案:

答案 0 :(得分:1)

使用适当的GROUP BYGROUP BY中必须包含所有未聚合的列。

SELECT MIN(amount), year
FROM salary
GROUP BY year

如果要包含行业名称,

SELECT amount, year, industryName, salaryId
FROM (
    SELECT amount, year, industryName, salaryId 
        , ROW_NUMBER() OVER(PARTITION BY year ORDER BY amount) AS rn
    FROM salary
 ) a
 WHERE rn = 1

MySQL 8之前的版本

SELECT *
FROM salary s
INNER JOIN (
    SELECT MIN(amount) AS minAmount, year
    FROM salary
    GROUP BY year
) m ON m.minAmount = s.amount AND m.year = s.year

答案 1 :(得分:0)

我认为您需要自我加入:

SELECT s1.industryName, s2.min_salary, s2.salaryYear
  FROM salary s1
  JOIN  
  (
   SELECT MIN(salary) as min_salary, salaryYear
    FROM salary
   GROUP BY salaryYear
   ) s2
    ON s1.salary = s2.min_salary
   AND s1.salaryYear = s2.salaryYear;

The Demo of this query with your sample data