无论如何以提高查询性能或任何其他方式

时间:2019-02-13 17:28:46

标签: sql sql-server database-performance

我已经存储了要优化查询的过程。我需要在同一临时表中为三种不同类型的数据设置数据。以下是我的查询

SET @Counter = -3;      
WHILE (@Counter <=-1)      
 BEGIN    
 insert into #tempTable (col1, col2,amount)
 select col1,col2,
  CASE 
      WHEN @Counter  = -2 THEN MAX(col3) --sample actual is different
      WHEN @Counter  = -3 then sum(Col3)
      WHEN @Counter  = -1 col3
    SET @Counter = @Counter + 1;      
      from   #tempTable where amount>100 
      group by col1,col2,amount
END

任何优化方法

2 个答案:

答案 0 :(得分:1)

为什么不简单地使用UNION ALL? :

INSERT INTO #tempTable (col1, col2, amount)
     SELECT col1, col2, MAX(col3)
     FROM #tempTable 
     WHERE amount > 100
     GROUP BY col1, col2
     UNION ALL
     SELECT col1, col2, SUM(col3)
     FROM #tempTable 
     WHERE amount > 100
     GROUP BY col1, col2 
     UNION ALL
     SELECT col1, col2, col3
     FROM #tempTable 
     WHERE amount > 100; 

答案 1 :(得分:0)

您可以计算金额的结果,然后使用左联接。

SET @Counter = -3;      
WHILE (@Counter <=-1)      
BEGIN    
    insert into #tempTable (col1, col2,amount)
    select 
        t1.col1, t1.col2,
        CASE 
            WHEN @Counter  = -2 THEN t1.MAX_COL3 
            WHEN @Counter  = -3 then t2.SUM_COL3
            WHEN @Counter  = -1 THEN t1.col3
        END AS amount
        SET @Counter = @Counter + 1;      
    FROM  #tempTable t1
    LEFT JOIN 
    (
        SELECT 
            col1, col2, 
            MAX(BillRate) AS MAX_COL3, 
            SUM(BillRate) AS SUM_COL3
        FROM #tempTable 
        GROUP BY col1, col2
    ) t2
        ON t1.col1 = t2.col1
        AND t1.col2 = t2.col2
    WHERE AMOUNT > 100 
END