2

我得到了这张表和一些数据:

SELECT Id, SubId, N1, N2, N3 FROM table1 WHERE Id = 2

Id          SubId    N1          N2          N3
----------- -------- ----------- ----------- ----------------------
2           1        94917       97030       0
2           2        35087       41306       0
2           3        189671      194224      0
2           4        44905       46218       0
2           5        65760       70959       0
2           6        620         2395        0
2           7        60336       69531       0
2           8        65517       70666       0

我运行这个查询

UPDATE table1
SET N3 = CASE WHEN N1 = 0 THEN 0 ELSE (( N2 * 1.0 / N1 ) -1) * 100 END

Id          SubId    N1          N2          N3
----------- -------- ----------- ----------- ----------------------
2           1        94917       97030       2.2261554832
2           2        35087       41306       17.7245133525
2           3        189671      194224      2.4004723969
2           4        44905       46218       2.9239505622
2           5        65760       70959       7.9060218978
2           6        620         2395        286.2903225806
2           7        60336       69531       15.2396579156
2           8        65517       70666       7.8590289543

因此,当我按 Id 对表进行分组时,我得到了以下数据:

SELECT  Id, 
        SUM(N1) AS N1, 
        SUM(N2) AS N2, 
        CAST(0 AS NUMERIC(10,2)) AS N3
INTO table2
FROM table1
GROUP BY Id

UPDATE table2
SET N3 = CASE WHEN N1 = 0 THEN 0 ELSE (( N2 * 1.0 / N1 ) -1) * 100 END

SELECT Id, N1, N2, N3 FROM table2 WHERE Id = 2

Id          N1          N2          N3
----------- ----------- ----------- ----------------------
2           556813      592329      6.38

问题是当我按 ID(6.38)分组而不重新计算字段(第二次更新)时,如何获得相同的 N3 值,我试图应用反向计算((N3/100)+1)并对 N3 求和场,但没有工作。

4

2 回答 2

2

只需将N1and分别替换N2SUM(N1)and SUM(N2)..

SELECT  Id, 
        SUM(N1) AS N1, 
        SUM(N2) AS N2, 
        N3 = CAST(CASE WHEN SUM(N1) = 0 THEN 0 ELSE (( SUM(N2) * 1.0 / SUM(N1) ) -1) * 100 END AS NUMERIC(10,2))
FROM table1
GROUP BY Id

演示在 http://sqlfiddle.com/#!3/de849/4/0

于 2012-12-26T18:05:37.987 回答
1
SELECT  Id,
        SUM(N1) AS N1,
        SUM(N2) AS N2,
        CAST(CASE WHEN SUM(N1) = 0 THEN 0 ELSE (( SUM(N2) * 1.0 / SUM(N1) ) -1) * 100 END AS NUMERIC(10,2))) as N3
FROM temp
GROUP BY Id

N3 需要将 Sum(N1) 和 Sum(N2) 作为值而不是 N1 和 N2,因为您是基于聚合而不是单个值计算 N3。

于 2012-12-26T18:11:24.257 回答