2016-07-06 80 views
0

多個列我將在下面組通過使用聚集函數

Budhol COCODE BEN  OBJ SPARE2 SPARE1 TASKNO Value FieldNameNew 
    362103 36  362101 991003 NULL MA1001 NULL 4516 613030 
    362103 36  362101 991003 NULL MA1001 NULL 9088 613030 
    362103 36  362101 991003 NULL MA1001 NULL 3387 613030 
    362103 36  362101 991003 NULL MA1001 NULL 4026 613030 

列出的下面的表結構下方是所需的輸出

Budhol COCODE BEN  OBJ SPARE2 SPARE1 TASKNO Value FieldNameNew 
    362103 36  362101 991003 NULL MA1001 NULL 21017 613030 

即,如果所有列都值應爲SUMED相同的,即所有價值列的總和

以下是查詢我已經嘗試過,但價值並不正確

SELECT B.BEN, 
     B.BUDHOL, 
     B.COCODE, 
     B.FIELDNAMENEW, 
     B.OBJ, 
     B.SPARE1, 
     B.SPARE2,  
     SUM(B.value)as Value into #temp4 
FROM (
    SELECT DISTINCT A.BEN, 
        A.BUDHOL, 
        A.COCODE, 
        A.FIELDNAMENEW, 
        A.OBJ, 
        A.value, 
        A.SPARE2, 
        A.SPARE1  
    FROM #temp3 A 
    LEFT JOIN #temp3 T1 ON A.BEN = t1.BEN 
     AND A.BUDHOL = t1.BUDHOL 
     AND A.COCODE = t1.COCODE 
     AND A.OBJ = t1.OBJ 
     AND A.SPARE1 = t1.SPARE1 
     AND A.SPARE2 = t1.SPARE2 
     AND A.FieldNameNew = t1.FieldNameNew 
) B 
GROUP BY B.BEN, 
     B.BUDHOL, 
     B.COCODE, 
     B.OBJ, 
     B.FIELDNAMENEW, 
     B.SPARE1, 
     B.SPARE2 

回答

1

根據你寫的,更簡單的查詢將工作:

SELECT B.BEN, B.BUDHOL, B.COCODE, B.FIELDNAMENEW, B.OBJ, B.SPARE1, B.SPARE2,  
     SUM(B.value) as Value 
into #temp4 
FROM #temp3 B 
GROUP BY B.BEN, B.BUDHOL, B.COCODE, B.FIELDNAMENEW, B.OBJ, B.SPARE1, B.SPARE2;