具有不同列的求和查询

sum query with distinct columns

这是我的 table batchmaster,包含批次名称、子批次名称、记录等列

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   records  
12032014     raw1_0     4  
12032014     raw1_1     4 
12302014     raw7_0   300 

尝试以下操作:

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

这对你有用

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

我同意 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 
 SELECT BatchName,SubBatch,SUM(records) AS Records
    FROM urTableName
  GROUP BY BatchName, SubBatch