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_timegreater 0casereturnsbooked_stop_time - booked_start_time, it's included in sum. - the
casedoesn't have other conditions, ifbooked_stop_time - booked_start_timenot greater zero,casereturns null, means row not included in sum.
Comments
Post a Comment