简体   繁体   中英

MySQL - find difference between fields in same column

I have a table containing first name, middle name, last name, year of birth, municipality and income details. The data set contains several years. The problem is that the data does not include a unique id per person.

Thus, I have to compare the same people based on the abovementioned data to find the same people for each year. Not exactly precise but there is no other way.

I'm trying to write a query that compare the income in one year with another to see how the income develops (drops, rises).

My try so far:

SELECT e.firstname, e.lastname, e.birth, e.middlename,
    e.income-n.income as incomediff 
    from incomedata e
LEFT JOIN 
    (select n.firstname, n.lastname, n.birth, n.middlename) as 
    ON e.firstname = n.firstname, e.lastname = n.lastname, e.birth = n.birth, e.middlename = n.middlename
    where e.municip=1234 and e.year IN (2011,2010);

This doesn't work (obviously), and I guess I cannot run a JOIN without a unique id. Any idea on how to sort this out?

Maybe you're looking for this:

SELECT e.firstname, e.lastname, e.birth, e.middlename,
    e.income - n.income as incomediff 
FROM incomedata e
LEFT JOIN incomedata n
    ON e.firstname = n.firstname 
    AND e.lastname = n.lastname
    AND e.middlename = n.middlename
    AND e.birth = n.birth
WHERE e.municip = 1234 
    AND e.year = 2011
    AND n.year = 2010

There's nothing wrong with doing JOINs on multiple fields, you just have to AND the conditions together instead of separating by commas like in your post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM