T-sql使用一个表中的值并将它们显示在不同的列中

时间:2013-10-09 18:36:22

标签: sql sql-server tsql

我的数据库表格如下:

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

我希望我的输出看起来是基于其索引的值列的差异 ie 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

我知道此查询存在问题。但我只是无法生成我想要的输出。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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]