使用带有if表达式的sql计算多个值

时间:2013-10-07 13:18:47

标签: mysql sql math

我有一个包含6列的预订表,名为booked_start,booked_stop,used_start,used_stop,invoice_start,invoice_stop。值是浮点数。我想得到一个值大于0的行的总和,但我也希望它计算说used_stop - used_start。

目前正在与此合作:

SELECT
    room,
    IF( booked_stop_time > 0, sum(booked_stop_time - booked_start_time), 0 ) as booked,
    IF( used_stop_time > 0, sum(used_stop_time - used_start_time), 0 ) as used,
    IF( invoice_stop_time > 0, sum(invoice_stop_time - invoice_start_time), 0 ) as invoice
FROM bookings

问题是如果expr1返回false,它将重置总和。我只想将行值添加到总和中,如果它高于0。

我也试过使用一个案例,但这并没有真正起作用。也许我应该在PHP中进行计算呢?

3 个答案:

答案 0 :(得分:2)

这应该有效:

SELECT
  room,
  SUM(
    CASE WHEN booked_stop_time - booked_start_time > 0
      THEN booked_stop_time - booked_start_time
      END
  ) AS booked,
  SUM(
    CASE WHEN used_stop_time - used_start_time > 0
      THEN used_stop_time - used_start_time
      END
  ) AS used,
  SUM(
    CASE WHEN invoice_stop_time - invoice_start_time > 0
      THEN invoice_stop_time - invoice_start_time
      END
  ) AS invoice
FROM bookings

关注booked值:

  • 如果booked_stop_time - booked_start_time大于零,则CASE会返回booked_stop_time - booked_start_time,因此它会包含在总和中。
  • CASE没有任何其他条件,因此如果booked_stop_time - booked_start_time 大于零,则CASE将返回NULL,这意味着该行不包括在总和中。

答案 1 :(得分:0)

你可以这样做:

SELECT
    room,
    SUM(IF( booked_stop_time > 0, booked_stop_time - booked_start_time, 0 )) as booked,
    SUM(IF( used_stop_time > 0, used_stop_time - used_start_time, 0 )) as used,
    SUM(IF( invoice_stop_time > 0, invoice_stop_time - invoice_start_time, 0 )) as invoice
FROM bookings

它返回0,因为当您的IF条件不满足时,它会将0设置为最终值,因此只需使用IF包裹SUM

答案 2 :(得分:0)

你可以试试这个

SELECT
    room,

    SUM( 
          IF( booked_stop_time > 0 and booked_start_time IS NOT NULL, 
                       (booked_stop_time - booked_start_time), 0 ) 
      ) AS booked,

   SUM( 
       IF(used_stop_time > 0 AND used_start_time IS NOT NULL,
                            (used_stop_time - used_start_time) , 0 ) 
      ) AS used,

   SUM(
        IF(invoice_stop_time > 0 AND invoice_start_time IS NOT NULL, 
                            (invoice_stop_time - invoice_start_time) , 0)   
       ) AS invoice

WHERE booked_stop_time > 0 
OR  used_stop_time > 0 
OR invoice_stop_time > 0