This scenario is based on a circuit in yet another question , and I am not interested in discussing the correctness of the circuit!
I am interested to know if there are any good methods in SQL Server to aggregate one column (below amount1 ) based on the separate value of another column ( id1 ).
Plan1 below twice scans table1, performs two aggregations with p_id, then combines the result. It seems that this can be improved. In some cases, query 2 may return the wrong result, but the plan is still worse!
Any ideas?
DDL
IF OBJECT_ID('tempdb..#table1') IS NOT NULL DROP TABLE #table1; IF OBJECT_ID('tempdb..#table2') IS NOT NULL DROP TABLE #table2; CREATE TABLE #table1 (id1 int primary key nonclustered, amount1 int, p_id int); CREATE CLUSTERED INDEX ix ON #table1 (p_id,id1); INSERT INTO #table1 SELECT 1,500,10 UNION ALL SELECT 2,700,20 UNION ALL SELECT 3,500,10 UNION ALL SELECT 4,450,20 UNION ALL SELECT 5,300,10; CREATE TABLE #table2 (id2 int primary key, amount2 int, id1 int); INSERT INTO #table2 SELECT 1,300,1 UNION ALL SELECT 2,200,1 UNION ALL SELECT 3,200,2 UNION ALL SELECT 4,500,2 UNION ALL SELECT 5,400,3 UNION ALL SELECT 6,150,4 UNION ALL SELECT 7,300,4 UNION ALL SELECT 8,300,5;
Request 1
WITH t1 AS (SELECT p_id,SUM(amount1) AS total1 FROM
Plan 1

Request 2
SELECT table1.p_id, FLOOR(SUM(DISTINCT amount1 + table1.id1/100000000.0)) AS total1, SUM(amount2) AS total2 FROM
Plan 2
