使用聚合函数对多个列进行分组

时间:2016-07-06 12:21:22

标签: sql sql-server sql-server-2008

我有下面列出的表格结构

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

即如果所有列都相同,即所有值列的总和

,则应该使用值

以下是我尝试的查询但价值未正确

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 个答案:

答案 0 :(得分: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;