【问题标题】:Mysql 'greater than(>)' query always returns 0Mysql '大于(>)' 查询总是返回 0
【发布时间】:2018-09-08 05:40:22
【问题描述】:

我正在处理一个要显示即将到来的日期数量的查询。即使有大于当前日期的日期,以下查询也会返回 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

【问题讨论】:

    标签: mysql date compare


    【解决方案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;
    

    您试图使用 sum 作为 CASE 表达式的谓词,这可能不是您想要的。请注意,我还选择了facility_id,因为您是按该列分组的。如果您想要对整个表格进行条件总和,请不要按设施进行选择或分组。

    【讨论】:

    • 非常感谢,一切正常。我已按 facility_id 分组,因为我想要关于各个设施的即将到来的日期的计数。
    猜你喜欢
    • 2017-02-11
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 2023-04-03
    • 2017-01-25
    • 2018-11-19
    相关资源
    最近更新 更多