【问题标题】:SQL query to show monthly booking total显示每月预订总额的 SQL 查询
【发布时间】:2015-04-19 20:18:54
【问题描述】:

我的表格中的数据如下..

我需要显示每月预订摘要

bookingdate   receipt
 01-02-2015     25
 01-02-2015     26

 01-03-2015     31
 01-03-2015     32
 01-04-2015     36

预期输出

Month             totalbooking
Feb - 2015             2
Mar - 2015             2
Apr - 2015             1

请帮助我实现我的预期输出...

我试过下面的查询工作,但显示月份的所有行......但我只需要显示所选月份的记录......

SELECT RE.bookingdate AS bookingdate
    ,COUNT(DISTINCT RE.receipt_no) As TotalCount
FROM receipt_entry RE
WHERE str_to_date(RE.bookingdate,'%d-%m-%Y') BETWEEN :fromdate AND :todate
    AND RE.city_name = :cityname
GROUP BY RE.bookingdate

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    考虑以下内容并根据需要进行更改

    mysql> select * from test ;
    +-------------+---------+
    | bookingdate | receipt |
    +-------------+---------+
    | 2015-02-01  |      25 |
    | 2015-02-01  |      23 |
    | 2015-03-01  |      10 |
    | 2015-03-01  |      12 |
    | 2015-04-01  |      21 |
    +-------------+---------+
    
    
    select 
    date_format(bookingdate,'%M - %Y') as `month`, 
    count(distinct receipt) as receipt 
    from test group by `month`;
    
    +-----------------+---------+
    | month           | receipt |
    +-----------------+---------+
    | April - 2015    |       1 |
    | February - 2015 |       2 |
    | March - 2015    |       2 |
    +-----------------+---------+
    

    您将日期保存为 varchar,因此需要在应用 date_format 之前使用 str_to_date 将它们转换为实际日期,而且我还看到了 where 子句,因此在这种情况下,您还需要使用 str_to_date 进行转换,一个好的做法是将日期保存在 mysql 原生数据类型中,例如 datedatetimetimestamp ,这让生活变得简单。

    【讨论】:

      【解决方案2】:

      this 是你所期望的吗?

      SELECT CONCAT(MONTH(str_to_date(receipt_entry.bookingdate,"%d-%m-%Y")),'-',YEAR(str_to_date(receipt_entry.bookingdate,"%d-%m-%Y"))) AS dat,count(*) as cnt
      FROM receipt_entry
      GROUP BY dat;
      

      注意:我建议您将日期存储在 MySQL 中的 DATE 数据类型中。您无需每次都调用str_to_date() 函数。

      另一个注意事项:我在那里使用 CONCAT() 只是为了在一个字段中连接月份和年份,以使其适应您想要的输出。最好只按两列分组:年和月

      【讨论】:

      猜你喜欢
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 2018-10-01
      • 2021-01-14
      相关资源
      最近更新 更多