2012-12-26 170 views
2

我得到這個表的一些數據:TSQL組通過計算

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 

所以,當我按標識表我得到這樣的數據:

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)和SUM N3字段,但不起作用。

+1

[offtopic]不應該將'FROM表2'作爲'FROM table2'嗎?[/ offtopic] –

回答

2

只需更換N1N2SUM(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
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需要有總和(N1)和總和(N2)作爲值而不是N1和N2,因爲您正在計算基於聚合的N3而不是單個值。