使用不同列进行求和

时间:2015-01-02 06:34:38

标签: c# sql-server-2005

这是我的表batchmaster,其中包含batchname,subbatchname,records

等列
BatchName    SubBatch   records     
12032014     raw1_0     2  
12032014     raw1_0     2  
12032014     raw1_1     2  
12032014     raw1_1     2     
12302014     raw7_0    150  
12302014     raw7_0    150  

我希望得到输出,例如使用不同的batchname,subbatch和不同子补丁的记录总和。

BatchName    SubBatch   records  
12032014     raw1_0     4  
12032014     raw1_1     4 
12302014     raw7_0   300 

4 个答案:

答案 0 :(得分:1)

这对你有用

SELECT BatchName,SubBatch,SUM(records) AS SumRecords
FROM batchmaster
GROUP BY BatchName, SubBatch

答案 1 :(得分:1)

我同意Conrad Lotz的询问。

试试这个

DECLARE @batch_master TABLE
  (
     BatchName VARCHAR(50),
     SubBatch  VARCHAR(50),
     records   INT
  )

INSERT INTO @batch_master
VALUES      ('12032014',
             'raw1_0',
             '2'),
            ('12032014',
             'raw1_0',
             '2'),
            ('12032014',
             'raw1_1',
             '2'),
            ('12032014',
             'raw1_1',
             '2'),
            ('12302014',
             'raw7_0',
             '150'),
            ('12302014',
             'raw7_0',
             '150')

SELECT *
FROM   @batch_master

SELECT batchname,
       subbatch,
       sum(records)
FROM   @batch_master
GROUP  BY batchname,
          subbatch 

答案 2 :(得分:1)

 SELECT BatchName,SubBatch,SUM(records) AS Records
    FROM urTableName
  GROUP BY BatchName, SubBatch

答案 3 :(得分:0)

尝试以下方法:

SELECT BatchName,SubBatch,SUM(records) AS Records
FROM Table
GROUP BY BatchName, SubBatch