Monday, March 12, 2012

find percentage of a field

HOW can i get the percentage for each rank?
http://shahabedeen.europe.webmatrixhosting.net/pic/persentile04.gifOh goody, I love this kind of problem!SELECT 1e2 * a.rank / (SELECT Sum(b.rank) FROM tblpoll AS b) FROM tblpoll AS aThe problem is that you need to cooerce the type change before you start doing the math instead of after the math is complete. I'll let you work out the details!

-PatP|||Pat, will the optimizer be smart enough to only run the subquery once? Probably, but I'd phrase it this way to be sure:

SELECT rank/TotalVotes
from tblpoll,
(SELECT Sum(rank) as TotalVotes FROM tblpoll) subquery

"1e2"? 100, right?|||Pat, will the optimizer be smart enough to only run the subquery once? Probably, but I'd phrase it this way to be sure:

SELECT rank/TotalVotes
from tblpoll,
(SELECT Sum(rank) as TotalVotes FROM tblpoll) subquery

"1e2"? 100, right?As long as the subquery isn't correlated, the optimizer will only run it once.

Yes, 1e2 is a floating point 100. In this case, the type is very important because you have to force the type coersion to occur before the division, not after it if you want to retain the fractional portion of the result.

-PatP|||Thanks pat...|||Dear guy,I have a new problem:
http://shahabedeen.europe.webmatrixhosting.net/pic/persentile05.gif
As u can see the float point is not beautiful enough,How can I reduce the float points to 2 number? :rolleyes: :D|||Round() (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_ra-rz_93z8.asp)

-PatP

No comments:

Post a Comment