Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Reuse Calculated values

Author  Topic 

Shinho
Starting Member

1 Post

Posted - 2006-11-14 : 11:33:54
What is the best code pratice to use do the following code,

SELECT
fo.no as LNum,
fo.name as LName,
sum(CASE fo.docnome WHEN "In" THEN fo.etotal ELSE 0 END) as In1,
sum(CASE fo.docnome WHEN "In2" THEN fo.etotal ELSE 0 END) as In2,
sum(In1+In2)/10 as inDec,
from fo group by fo.no,fo.name order by fo.name

instead of

SELECT
fo.no as LNum,
fo.name as LName,
sum(CASE fo.docnome WHEN "In" THEN fo.etotal ELSE 0 END) as In1,
sum(CASE fo.docnome WHEN "In2" THEN fo.etotal ELSE 0 END) as In2,
((sum(CASE fo.docnome WHEN "In" THEN fo.etotal ELSE 0 END))+sum(CASE fo.docnome WHEN "In2" THEN fo.etotal ELSE 0 END)))/10 as inDec,
from fo group by fo.no,fo.name order by fo.name

I cant use functions and procedures. Is there any better and cleaner way to code this, reusing the calculated values?

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2006-11-14 : 11:43:57
I would use a derived table like this
SELECT		[No],
[Name],
In1,
In2,
(In1 + In2) / 10.0 AS inDec
FROM (
SELECT [No],
[Name],
SUM(CASE DocNome WHEN 'In' THEN eTotal ELSE 0 END) AS In1,
SUM(CASE DocNome WHEN 'In2' THEN eTotal ELSE 0 END) AS In2
FROM fo
GROUP BY [No],
[Name]
) g
ORDER BY [Name]


Peter Larsson
Helsingborg, Sweden
Go to Top of Page
   

- Advertisement -