简体   繁体   English

查询从两个不同的年份列中减去值?

[英]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): 每个位置ID恰好有两行(不一定按顺序):

+------+---------------------------------------+
| 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: 像这样的东西(如果这实际上是有效的MySQL语法,它将返回100),但是它必须适用于所有行:

(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: 如果确保同一location_id恰好有两行,则可以这样操作:

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. 此查询确保具有相同位置ID的两行以这样的方式连接在一起: data较小的那一行位于a侧, b则位于b侧。

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: 使用join连接表的两个实例,并添加一个减法列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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