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