1

我的数据库表如下所示:

ID | INDEX | Value |
1  |   0   |   3   |
1  |   1   |   5   |
1  |   2   |   7   |
2  |   0   |   4   |
2  |   1   |   6   |
2  |   2   |   2   |

我希望我的输出看起来像基于它们的索引的值列的差异,即 value(id=2,index = i) - value(id = 1, index = i) 所以输出表看起来像

INDEX | Delta Value |
  0   |     1       |
  1   |     1       |
  2   |    -5       |

我解决这个问题的尝试如下:

SELECT Top 6
    col1.value column1,
    col2.value column2,
    col2.value - col1.value
FROM My_Table col1
INNER JOIN  My_Table col2
    ON col1.index = col2.index 
WHERE col1.id = 1 
    OR col2.id = 2

我知道这个查询有问题。但我只是无法产生我想要的输出。任何帮助表示赞赏。

4

3 回答 3

3

你可以通过加入来做到这一点

select
    t1.ind, t1.value - t2.value as delta
from My_Table as t1
    inner join My_Table as t2 on t2.id = 2 and t2.ind = t1.ind
where t1.id = 1

或者通过简单的聚合:

select
    ind, sum(case id when 1 then 1 when 2 then -1 end * value) as delta
from My_Table
group by ind
于 2013-10-09T18:46:05.280 回答
0

你想要这样的东西吗?

select
    col1.value column1,
    col2.value column2,
    col2.value - col1.value AS delta
From My_Table col1
INNER JOIN  My_Table col2 
    ON col1.index = col2.index
    AND col2.id = 2 
where col1.id = 1
于 2013-10-09T18:49:16.547 回答
0

看看我的

 select t1.[index],
    t2.value-t1.value
 from my_table t1 inner join my_table t2
 on t1.[index] = t2.[index]
 where t1.id = 1 and t2.id = 2
 order by t1.[index]
于 2013-10-09T19:20:56.357 回答