views:

169

answers:

3

I have 3 columns in my db table, I need to multiply column, itm_count & itm_price and output the total for a given id(itm_id).

SELECT sum(itm_price * itm_count) as total FROM ods_temporder WHERE itm_id='11'

I tried to do this using the above sql query, but the result was null. What seems to be the issue here?

+5  A: 

What do this give you?

SELECT itm_price, itm_count FROM ods_temporder WHERE itm_id='11'

Is either of itm_price or itm_count NULL? Do you have rows for itm_id = 11?

gbn
@gbn-I made a stupid mistake, there's no column named itm_id. Thanks for pointing it out. When I changed it, the sql query worked fine. thnx
pier
Shouldn't you have received a syntax error of sorts then? Unless you were doing this through a front end which isn't properly catching errors.
Tom H.
@Tom H.- Yes, I first tested it using phpmyadmin
pier
A: 

What does itm_price and itm_count contain when itm_id= 11? Is this SQL Server? If so you can use ISNULL to handle whether itm_price or itm_count is null

JonH
Use COALESCE() instead of ISNULL(). It's ANSI standard, so works with other vendors as well. Syntax and semantics are identical, so there's no reason to keep using ISNULL().
Dewayne Christensen
+3  A: 

Try:

SELECT SUM(COALESCE(itm_price, 0) * COALESCE(itm_count, 0)) as total 
  FROM ods_temporder 
 WHERE itm_id='11'

COALESCE is an ANSI standard for dealing with NULL values - if itm_price or itm_count is null, zero will be used in this case as the value. Otherwise, either you don't have a row with a value of 11 for the itm_id column, or you're looking for the 11 value in the wrong column.

OMG Ponies
@OMG Ponies-:) Thanks that term was helpful.
pier