我有storedprocedure我想优化查询。我需要在同一个临时表中设置三种不同类型的数据。下面是我的查询
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
任何优化它的方法
为什么不简单地使用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;
您可以计算金额的结果,然后使用左连接。
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