Tricky sql涉及行计算

时间:2013-09-20 21:03:13

标签: sql-server sql-server-2008

需要计算名为Value的字段。

X0的计算逻辑:X1/X2 5/10 = 0.5 Y0的计算逻辑:Y1/Y2 4/10 = 0.4

以下是示例数据

ID Cd format Value
1  X1 #       5     
2  X0 %       0.5 --this needs to be computed based on X1/X2
3  X2 #       10
4  Y1 #       4     
5  Y0 %       0.4 --this needs to be computed based on Y1/Y2 
6  Y2 #       10

我如何在SQL中编写

谢谢!

2 个答案:

答案 0 :(得分:1)

这假设至少在x0列存在CD值。如果不是这种情况,则需要INSERT,这有点不同。

update u  set value  = p.value/q.value
from
theTable u
left join theTable p on left(u.CD, len(u.CD)-1)+'1' = p.CD   --  can be  left(u.CD, 1)+'1' = p.CD   if it is allways only one letter
left join theTable q on left(u.CD, len(u.CD)-1)+'2' = q.CD   --  can be  left(u.CD, 1)+'2' = q.CD   if it is allways only one letter
where right(u.CD,1) = '0'            -- if needed, you can also check CD lenght = 2
  and p.value/q.value  is not null   -- this avoids missing joins and dividing by 0
                                     -- but can be removed if null is desired for that case

答案 1 :(得分:0)

使用数据透视表:

WITH cte AS (SELECT * FROM (VALUES
   (1, 'X1', '#', 5  ),   
   (2, 'X0', '%', 0.5), --this needs to be computed based on X1/X2
   (3, 'X2', '#', 10 ),
   (4, 'Y1', '#', 4  ),   
   (5, 'Y0', '%', 0.4), --this needs to be computed based on Y1/Y2 
   (6, 'Y2', '#', 10 )

) AS x(id, cd, [format], [value]))

SELECT p.*, 1.0*[x1]/[x2] AS [x0], 1.0*[y1]/[y2] AS [y0]
FROM 
(SELECT cd, [value] FROM cte) AS c
PIVOT
(MAX([value])
FOR cd IN ([x1], [x2], [y1], [y2])) AS p

从那里,如果您需要表中的x0和y0,那么这是一个简单的更新。