2015-04-17 62 views
2

数据..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帮助我为了实现我的期望输出...

我试过下面曲ERY工作,但显示5月的行...但我需要显示选择的月份只记录......

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 

回答

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()那里才串联月和年在一个领域,以使其适应您所需的输出。更好的只是一群由两列:年份和月份

+0

查询是完美的,我认为,但如何呼应此日期格式...月 - 2015年不喜欢这个... 2-2015 –

+0

看到更新后的小提琴:http://sqlfiddle.com/#!9/e59b3/9,在这里:http://stackoverflow.com/questions/7027129/mysql-monthname-from-numbers – Alexey

+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因此需要应用之前,将它们转换为使用str_to_date真正的约会DATE_FORMAT,也是我看到一个where子句所以在这种情况下,你也需要做使用str_to_date转换,一个好的习惯是保存在MySQL原生数据类型日期像datedatetimetimestamp,这使得生活简单。