我正在处理一个查询,该查询要显示即将到来的日期数。即使日期大于当前日期,以下查询也会返回0。请帮我解决这个问题。
SELECT (case when b.booked_date > cast(now() as date) then sum(1) else sum(0) end) as upcoming_booked_facilities
from svk_apt_book_facilities b
where b.customer_id = 1
and b.association_id = 1
and b.is_active = 1
group by b.facility_id
答案 0 :(得分:1)
您需要对CASE
表达式求和以进行条件聚合:
SELECT
facility_id,
SUM(CASE WHEN booked_date > CURDATE() THEN 1 ELSE 0 END) AS upcoming_booked_facilities
FROM svk_apt_book_facilities
WHERE
customer_id = 1 AND
association_id = 1 AND
is_active = 1
GROUP BY
facility_id;
您试图将总和用作CASE
表达式的谓词,这可能不是您想要的。请注意,由于您要按该列分组,因此我也选择了facility_id
。如果您想在整个表格中使用条件总和,则不要按功能选择或分组。