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

时间:2015-07-25 18:50:27

标签: mysql sql

我有一个返回数据集的查询,该数据集返回两年不同的结果。每个位置id恰好有两行(不一定按顺序):

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

我想获取每年的结果,并从较晚年份的数据列中减去前一年的数据列。

像这样的东西(如果这实际上是有效的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 )

3 个答案:

答案 0 :(得分:2)

如果您保证同一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

此查询可确保具有相同位置ID的两行以这样的方式连接在一起,即data侧较小的a位于b侧,而b位于GET index_5589b14f3004fb6be70e4724/document_set/382.txt/_termvector { "fields" : ["plain_text", "pdf_text"], "term_statistics" : true, "field_statistics" : true } ... "advis": { //porter stemmed version of the word "advising" "doc_freq": 1, "ttf": 1, "term_freq": 1, "tokens": [ { "position": 81, "start_offset": 412, "end_offset": 420 } ] },... "air": { 方面。

Demo.

答案 1 :(得分:1)

您可以使用条件聚合执行此操作:

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;

答案 2 :(得分:1)

使用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
相关问题