根据报告生成结果集

时间:2014-03-27 18:25:36

标签: mysql sql count reporting aggregate-functions

如何使用MYSQL生成以下报告?

我的表'预订'看起来像这样:

id | arrival   | created.
1  | 2014-3-30 | 2014-3-1
2  | 2014-3-31 | 2014-3-2
3  | 2014-3-28 | 2014-3-2
4  | 2014-3-01 | 2014-3-1
5  | 2014-3-01 | 2014-3-1

我想为整个月的“到达”列生成以下两个汇总报告,如下所示:

(1)

     arrival     | count  | total_monthly_arrivals
     2014-03-01  | 2      | 5
     2014-03-02  | 0      | 5
     2014-03-03  | 0      | 5
     ...
     2014-03-30  | 1      | 5
     2014-03-31  | 1      | 5

(2)

    January     | 5
    ...
    March       | 5
    ...
    December    | 0      | 5

我想要这两个结果集。它根据&生成日期。按月报告,并以这些形式生成结果集。

我尝试在第一个结果集中使用group by with count但是它不检索不存在的日期。再次,我想把月份条件这样我选择月份。其中month = '02'或类似的东西。这可能吗?

1 个答案:

答案 0 :(得分:0)

我的SQLFiddle应该回答你问题的两个部分:http://sqlfiddle.com/#!2/9f130/31

这将返回到达日期,其中包含当天有多少人入住以及每月有多少人到达

select distinct(r.arrival) as arrival_date,
count(r.arrival) as total_per_day,
sa.month_total as total_arrival_per_month
from reservations as r
  ,(select substr(arrival,6,2) as month,
    count(substr(arrival,6,2)) as month_total
    from reservations
    group by month) as sa
where substr(r.arrival,6,2) = sa.month
group by arrival_date,total_arrival_per_month;

这将返回一年中的月份以及当月预订的人数以及当月有多少人。 (根据agrizzo的建议更新了。)

select MONTHNAME(STR_TO_DATE(substr(r.arrival,6,2), '%m')) as arrival_date,
sa.month_total as total_arrival_per_month
from reservations as r
  ,(select substr(arrival,6,2) as month,
    count(substr(arrival,6,2)) as month_total
    from reservations
    group by month) as sa
where substr(r.arrival,6,2) = sa.month
group by arrival_date,total_arrival_per_month;

但是,如果没有由您提供和预先填写的完全合格的数据集,我无法在一年中的每一天/每月给您。那是你要做的并为我们提供。

但是,您可以查看此主题。 Get a list of dates between two dates并在查询中利用他们的信息来获得所需的结果。