简体   繁体   中英

Query to subtract values from two different year columns?

I have a query that returns a dataset that returns results for two different years. There will be exactly two rows per location id (not necessarily in sequence):

+------+---------------------------------------+
| year   | location_id |  unique_1  | data
+------+---------------------------------------+
| 1990   | 100         |  343       | 100
| 2000   | 100         |  343       | 200
| 1990   | 55          |  111       | 50
| 2000   | 55          |  111       | 60

I want to take the results for each of the years and subtract the data column from the earlier year's from the data column from the later year's row.

Something like this (which would return 100 if this was actually valid MySQL syntax), but it would need to be for all rows:

(SELECT data FROM TABLE 
 WHERE year = 2000
 AND location_id = 100
 AND unique_1 = 343 )

MINUS

(SELECT data FROM TABLE 
 WHERE year = 1990
 AND location_id = 100
 AND unique_1 = 343 )

If you are guaranteed that there are exactly two rows for the same location_id , you can do it like this:

select
    a.location_id
,   b.data - a.data
from test a
join test b on a.location_id=b.location_id and a.data>b.data

This query ensures that two rows with the same location ids get joined together in such a way that the one with smaller data is on the a side, and b is on the b side.

Demo.

You can do this using conditional aggregation:

select t.location_id,
       max(case when t.year = 2000 then data
                when t.year = 1999 then - data
           end) as diff
from table t
group by t.location_id;

use join to connect two instances of the table, and add a subtraction column:

select first.location_id, first.unique_1, first.data - second.data as result
from (SELECT data FROM TABLE WHERE year = 2000) as first join 
(SELECT data FROM TABLE WHERE year = 1990) as second on first.location_id = 
second.location_id and first.unique_1 = second.unique_1

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