I need to sum some rows applying on each row a formula and after all sum in a last column all the results. I’d like that in the total column I didn’t have to especify the previous formulas but use the name of the column, I mean something like the following code (which doesn’t work because total_1, total_2 and total_3 are not recognized)
SELECT
t.id,
t.dpt,
sum(t1.coefficient * t1.value) AS total_1,
sum(t2.coefficient * t2.value) AS total_2,
sum(t3.coefficient * t3.value) AS total_3,
(total_1 + total_2 + total_3) AS total -- Not recognized
FROM my table t
JOIN table1 t1 ON...
JOIN table2 t2 ON...
JOIN table3 t3 ON...
group by t.id, t.dpt
I know I could do something like thefollowing, but it emplies some redundancy in the definitions of the sums.
SELECT
t.id,
t.dpt,
sum(t1.coefficient * t1.value) AS total_1,
sum(t2.coefficient * t2.value) AS total_2,
sum(t3.coefficient * t3.value) AS total_3,
sum(t1.coefficient * t1.value + t2.coefficient * t2.value + t3.coefficient * t3.value) AS total
FROM my table t
JOIN table1 t1 ON...
JOIN table2 t2 ON...
JOIN table3 t3 ON...
group by t.id, t.dpt
Is there any efficient query which can be helpful to avoid redefining the columns sums in the total column?
Thanks
The simplest way I think of is:
Added:
I’ve tested queries like bellow (I know that they differ, but you should test in on your own it’s the best way to spot the difference). Before each run I’ve executed
DBCC DROPCLEANBUFFERSandDBCC FREEPROCCACHE. 2nd run were executed after few minutes and the difference is due to the server load probably.1st query 1st run:
1st query 2nd run:
2nd query 1st run:
2nd query 2nd run: