Calculate column value in sql

I have a table in MySQL db that looks like this:

SELECT * FROM pi;

Employee_id Year 1000 2014 1000 2015 1001 2014 1002 2014 1002 2015 1003 2015 1004 2015

When I run the following query:

SELECT Employee_id, MIN(Year) FROM pi GROUP BY Employee_id;

I get:

Employee_id Year 1000 2014 1001 2014 1002 2014 1003 2015 1004 2015

Now I want to add a new column to the original table values, which should be "0" if the Year value for the row is MIN (Year) for Employee_id or "1" if it is not "t. I tried:

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;

      

And this gives:

Employee_id Year New 1000 2014 0 1001 2014 0 1002 2014 0 1003 2015 0 1004 2015 0

On the other hand, when I tried:

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;

      

I just:

Employee_id Year New 1000 2014 1

I tried a bunch of additional queries, but they all displayed error messages or the same results as the ones I had, so I kind of got stuck here. Any suggestions? Thank.

+3


source to share


1 answer


You can use the ond join of the min table



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

      

+1


source







All Articles