Jeff
Jeff

Reputation: 882

Sum Function with division

I am trying to figure out which is the correct format when using the sum function with division:

Which one is correct?

sum(filesize/1024)

or

sum(filesize)/1024

The filesize column is a measurement in kilobytes which I am converting to megabytes.

Upvotes: 0

Views: 1751

Answers (4)

JohnK813
JohnK813

Reputation: 1124

Logically, both should give the same result. However, sum(filesize)/1024 will probably be faster. If you go with the other option, you're performing the divide operation on each result, instead of just doing it once.

Upvotes: 0

Ian Jacobs
Ian Jacobs

Reputation: 5501

Personally I'd go with option #2 (assuming the number's aren't so large you'll have overflow issues to deal with). This way the numbers stay as exact as possible until they're given to the user.

Upvotes: 1

Nick Ruisi
Nick Ruisi

Reputation: 11

I'm pretty sure the first one is correct - sum(filesize/1024), but you'll want to make sure that filesize is never 0, or your query will error.

Use decode on oracle or if on SQL server to do that.

Upvotes: 0

Andomar
Andomar

Reputation: 238086

They mean different things. sum(filesize/1024) reduces the file size to megabytes, and then sums megabytes. For each file, this "forgets" the size in excess of the megabytes boundary, so it will underreport the total file size.

sum(filesize)/1024 will report the correct size in megabytes-- rounded down.

Upvotes: 7

Related Questions