存储过程,用于选择表1,分组依据,总和中的值,然后将这些值插入到表2中

时间:2019-07-16 01:25:11

标签: sql sql-server aggregate

我需要一个存储过程来从一个表中选择行,进行Group BySum,然后将结果及其值插入到另一个表中。

我想我必须在rfds_processing_id(类似于订单号)匹配现有行时进行合并,而在不匹配时进行插入。我目前在控制器中的Linq中执行类似的操作,但是无法在SQL中弄清楚。

ALTER PROCEDURE [dbo].[ProposedSummary]
    (@rfds_processing_id UNIQUEIDENTIFIER = NULL)
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO Summary_Proposed(model, type, elevation, qty)
        SELECT model, type, elevation, SUM(qty)
        FROM Current_Antenna C
        WHERE C.rfds_processing_id = @rfds_processing_id
        GROUP BY C.model
END

这就是我在Controller中执行的操作,并将其发送到View

var summary_c = current
    .Where(x => !string.IsNullOrWhiteSpace(x.model) && (x.rfds_processing_id == ))
    .GroupBy(x => x.model)
    .Select(x =>
    {
        var c = new
        {
            model = x.Key,
            type = x.Select(y => y.type).First(),
            elevation = x.Select(y => y.elevation).First(),
            qty = x.Sum(y => y.qty)
        };
        return c;
    }).ToList();

这是第一部分正常工作的更新

INSERT INTO Summary_Current(model, type, elevation, rfds_processing_id, qty)
    SELECT model, type, elevation, rfds_processing_id, SUM(qty)
    FROM Current_Antenna C
    WHERE C.rfds_processing_id = @rfds_processing_id 
      AND C.model != '' 
      AND C.type IS NOT NULL 
      AND C.elevation IS NOT NULL
GROUP BY C.model, C.type, C.elevation, rfds_processing_id

2 个答案:

答案 0 :(得分:6)

您当前的处理程序对我来说还可以,除了GROUP BY子句应包含所有也出现在SELECT中的非聚合列:

INSERT INTO Summary_Proposed(model, type, elevation, qty)
SELECT model, type, elevation, SUM(qty)
FROM Current_Antenna C
WHERE C.rfds_processing_id = @rfds_processing_id AND
      C.type IS NULL AND C.elevation IS NULL
GROUP BY C.model, C.type, C.elevation;

答案 1 :(得分:0)

最好将try catch块用于插入事务

   begin transaction 
        INSERT INTO Summary_Proposed(model, type, elevation, qty)
        SELECT model, type, elevation, SUM(qty)
        FROM Current_Antenna C
        WHERE C.rfds_processing_id = @rfds_processing_id AND
        C.type IS NULL AND C.elevation IS NULL
        GROUP BY C.model, C.type, C.elevation;
   commit transaction 
 --Alert success message 
   end try  
   begin catch 
-- Alert error message 
   end catch