2

需要在下面计算一个名为 Value 的字段。

: =的 计算逻辑: X0=X1/X2 5/10的计算逻辑0.5Y0Y1/Y2 4/100.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 中编写这个

谢谢!!

4

2 回答 2

1

这至少假设x0column 存在值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
于 2013-09-20T21:37:14.990 回答
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,只需简单更新即可。

于 2013-09-21T02:06:30.070 回答