【问题标题】:Get number of entries per month in MySQL database获取 MySQL 数据库中每月的条目数
【发布时间】:2020-04-26 21:03:54
【问题描述】:

我有一个 MySQL 数据库,其中包含两列的预订:

BookingDate (datetime)
Status (varchar with the values of Confirmed, Open, Unconfirmed, Closed, Canceled)

我想统计每个月状态为已关闭、已打开或已确认的条目数。稍后我将使用 PHP 将这些数据导出到图表中,因此我需要将其传递到数组中。

在 MySQL 中执行此操作的最佳方法是什么?我希望结果如下所示:

mm/yy -> # of entires

【问题讨论】:

    标签: mysql database date count pivot


    【解决方案1】:

    考虑:

    select date_format(booking_date, '%m/%y'), count(*) nb_entries
    from mytable
    where status in ('Closed', 'Open', 'Confirmed')
    group by year(booking_date), month(booking_date), date_format(booking_date, '%m/%y')
    order by year(booking_date), month(booking_date)
    

    如果您希望每个状态有一列,那么:

    select 
        date_format(booking_date, '%m/%y'), 
        count(*) nb_entries,
        sum(status = 'Closed') nb_entries_closed,
        sum(status = 'Open') nb_entries_open,
        sum(status = 'Confirmed') nb_entries_confirmed
    from mytable
    where status in ('Closed', 'Open', 'Confirmed')
    group by year(booking_date), month(booking_date), date_format(booking_date, '%m/%y')
    order by year(booking_date), month(booking_date)
    

    【讨论】:

    • 太棒了!这完全可行,还有一个问题 - 如果我添加另一行带有“la”或“ny”选项的“city”,我将如何只选择 la?
    • @tony: where status in ('Closed', 'Open', 'Confirmed') and city = 'la'
    • 再问你一个问题:如果我想做两个不同的输出。一个输出,另一个输出已关闭的预订,我该怎么做?
    • 所以基本上有 mm/yy -> 关闭/打开/确认的数量 -> 取消/未确认的数量
    【解决方案2】:
    SELECT DATE_FORMAT(booking_date, '%m/%y') `month and year`, 
           SUM(status IN ('Closed', 'Open', 'Confirmed')) `# of entires`
    FROM `booking reservations`
    -- WHERE city = 'LA'
    GROUP BY DATE_FORMAT(booking_date, '%m/%y')
    

    【讨论】:

    • 太棒了!这完全可行,还有一个问题 - 如果我添加另一行带有“la”或“ny”选项的“city”,我将如何只选择 la?
    • 再问你一个问题:如果我想做两个不同的输出。一个输出,另一个输出已关闭的预订,我该怎么做?
    • 所以基本上有 mm/yy -> 关闭/打开/确认的数量 -> 取消/未确认的数量
    • @tony 添加一个带有其他条件的输出字段:SUM(status IN ('Canceled', 'Unconfirmed'))...
    • 我如何按日期排序?最旧到最新?
    猜你喜欢
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 2014-10-12
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多