mysql - Calculate multiple values with sql with if expression -


i have booking table 6 columns called booked_start, booked_stop, used_start, used_stop, invoice_start, invoice_stop. values floats. want sum of rows has values above 0 want calculate used_stop - used_start.

currently im working this:

select     room,     if( booked_stop_time > 0, sum(booked_stop_time - booked_start_time), 0 ) booked,     if( used_stop_time > 0, sum(used_stop_time - used_start_time), 0 ) used,     if( invoice_stop_time > 0, sum(invoice_stop_time - invoice_start_time), 0 ) invoice bookings 

the problem if expr1 returns false it'll reset sum. want add rows value sum if above 0.

i tried using case didnt work. maybe should calculation in php instead?

this should work:

select   room,   sum(     case when booked_stop_time - booked_start_time > 0       booked_stop_time - booked_start_time       end   ) booked,   sum(     case when used_stop_time - used_start_time > 0       used_stop_time - used_start_time       end   ) used,   sum(     case when invoice_stop_time - invoice_start_time > 0       invoice_stop_time - invoice_start_time       end   ) invoice bookings 

focusing on booked value:

  • if booked_stop_time - booked_start_time greater 0 case returns booked_stop_time - booked_start_time, it's included in sum.
  • the case doesn't have other conditions, if booked_stop_time - booked_start_time not greater zero, case returns null, means row not included in sum.

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -