TSQL分组计算

时间:2012-12-26 17:55:07

标签: sql-server math group-by

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

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字段但不起作用。

2 个答案:

答案 0 :(得分:2)

只需将N1N2分别替换为SUM(N1)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

答案 1 :(得分: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而不是单个值。