3

我有一个包含 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 中进行计算?

4

3 回答 3

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大于零,则返回NULL,这意味着该行CASE包括在总和中。
于 2013-10-07T13:28:32.810 回答
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为最终值,所以只需将 with 包装IF起来SUM

于 2013-10-07T13:26:47.457 回答
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
于 2013-10-07T13:55:19.833 回答