行值的算术运算

时间:2017-07-17 09:26:42

标签: sql sql-server

我有一张包含以下数据的表格

Tid   Did    value
------------------
1     123    100
1     234    200
2     123    323
2     234    233

所有tid都有did为123和234.因此,对于每个有did 123和234的tid,我想计算value of did 123 / value of did 234 * 100,即100/200 * 100 对于tid 2,它将是value of did 123 / value of did 234 * 100,即323/233 * 100

输出表将是

Tid   result
------------------
1     100/200 * 100
2     323/233 * 100

任何帮助?

4 个答案:

答案 0 :(得分:1)

JOIN“123”行,带有“234”行:

select t123.tid, t123.value * 100 / t234.value
from
  (select tid, value from tablename where value = 123) t123
join
  (select tid, value from tablename where value = 234) t234
  on t123.tid = t234.tid

答案 1 :(得分:0)

select tid,
       100 * sum(case when did = 123 then value end) / 
             sum(case when did = 234 then value end)
from your_table
group by tid
having sum(case when did = 234 then value end) > 0

答案 2 :(得分:0)

加入,全部在ON

select t123.tid, t123.value * 100 / t234.value
from tablename t123
join tablename t234 on t123.tid = t234.tid and t123.did = 123 and t234.did = 234

答案 3 :(得分:0)

这是查询。我们可以使用内连接来实现它。

SELECT T1.Tid,(T1.value/T2.value)*100 AS Result 
FROM Table_1 AS T1
INNER JOIN
Table_1 AS T2
ON (T1.Tid = T2.Tid) 
AND (T1.Did <> T2.Did) 
AND T1.Did = 123