SQL查询显示每月预订总数

时间:2015-04-17 13:15:06

标签: mysql sql

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

我需要显示每月预订摘要

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

PLZ帮助我达到预期的输出......

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

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

2 个答案:

答案 0 :(得分: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,一个好的做法是在datedatetimetimestamp等mysql原生数据类型中保存日期,这会让生活变得简单。

答案 1 :(得分:0)

你期待的是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()只在一个字段中连接月份和年份以使其适应您想要的输出。最好只分两列:年和月