我在MySQL数据库中有一个表格,如下所示:
SELECT * FROM pi;
Employee_id Year
1000 2014
1000 2015
1001 2014
1002 2014
1002 2015
1003 2015
1004 2015
当我运行以下查询时:
SELECT Employee_id, MIN(Year)
FROM pi
GROUP BY Employee_id;
我明白了:
Employee_id Year
1000 2014
1001 2014
1002 2014
1003 2015
1004 2015
现在我想在原始表值中添加一个新列,该列应具有' 0'如果行的Year的值等于Employee_id的MIN(Year)或者' 1'如果它没有。我试过了:
SELECT Employee_id, MIN(Year),
(CASE WHEN(SELECT MIN(Year) FROM pi WHERE Employee_id = Employee_id < Year) THEN '0' ELSE '1' END) New
FROM pi
GROUP BY Employee_id;
这会产生:
Employee_id Year New
1000 2014 0
1001 2014 0
1002 2014 0
1003 2015 0
1004 2015 0
另一方面,当我尝试时:
SELECT Employee_id, MIN(Year),
(CASE WHEN(SELECT MIN(Year) FROM pi
WHERE Employee_id = Employee-id
GROUP_BY employee_id < Year) THEN '0' ELSE '1' END) New
FROM pi;
我得到了:
Employee_id Year New
1000 2014 1
我已经尝试过一堆额外的查询,但是所有这些查询都会显示错误消息或者结果与这两个相同,所以我有点卡在这里。有什么建议? 谢谢。
答案 0 :(得分:1)
你可以在最小桌上使用连接
select t.Employee_id, t.min_year
, case when pi.year = t.min_year then 0 else 1 end as my_check
from pi inner join (
SELECT Employee_id, MIN(Year) as min_year
FROM pi
GROUP BY Employee_id
) t on t.Employee_id = pi.Employee_id