2016-11-14 92 views
-1

我有这样的方案:集团按日期每10天

+----+--+--------+--------------------+ 
| ID | Amount |  paydate  | 
+----+-----------+--------------------+ 
| 1 | 200 |2016-11-05   | 
+----+-----------+--------------------+ 
| 2 | 3000 |2016-11-10   | 
+----+-----------+--------------------+ 
| 3 | 2500 |2016-11-11   | 
+----+-----------+--------------------+ 
| ID | 100  |2016-11-21   | 
+----+-----------+--------------------+ 
| 1 | 200 |2016-11-22   | 
+----+-----------+--------------------+ 
| 2 | 3000 |2016-11-23   | 
+----+-----------+--------------------+ 
| 3 | 2500 |2016-11-29   | 
+----+-----------+--------------------+ 

我怎样才能获得通过,每10天就像从每月第一天的分组,以10日的总金额,然后从11日至20日和21日到月底?

要显示这样的:

+-----------+------------------------+ 
| Amount |  paydate   | 
+-----------+------------------------+ 
| 3200 |2016-11-1 to 2016-11-10 | 
+-----------+------------------------+ 
| 2500 |2016-11-11 to 2016-11-20| 
+-----------+------------------------+ 
| 5800 |2016-11-21 to 2016-11-31|  
+-----------+------------------------+ 

我试图

SELECT 
    SUM(Amount) AS Amount, 
    year(Facture.paydate) AS Annee, 
    month(Facture.paydate) AS Mois 
FROM Facture 
GROUP BY year(Facture.paydate), month(serFacture.paydate) 

但是这并没有给我结果,我需要。

+0

添加几月的日期,也许还有一些2015年的日期。 – jarlh

+1

使用日历表,即,一张包含你想要的日期的表格。然后加入并分组。 – Ben

+0

@Ben如何?你可以举个例子 –

回答

1
select  sum(Amount) as sum_amount 
      ,case 
       when day(paydate) <= 10 then concat(DATE_FORMAT(paydate,'%Y-%m-01'),' to ',DATE_FORMAT(paydate,'%Y-%m-10')) 
       when day(paydate) <= 20 then concat(DATE_FORMAT(paydate,'%Y-%m-11'),' to ',DATE_FORMAT(paydate,'%Y-%m-20')) 
       else concat(DATE_FORMAT(paydate,'%Y-%m-21'),' to ',DATE_FORMAT(paydate,'%Y-%m-31')) 
      end as paydate_period 

from  t 

group by paydate_period 
; 

sum_amount paydate_period 
3200  2016-11-01 to 2016-11-10 
2500  2016-11-11 to 2016-11-20 
5800  2016-11-21 to 2016-11-31 
+0

非常感谢你这项工作perfectrly –

1

下面是一个例子查询:

select 
case 
    when day(date_field) between 1 and 10 then "01 to 10" 
    when day(date_field) between 11 and 20 then "11 to 20" 
    when day(date_field) between 21 and 31 then "21 to 31" 
end as the_range, 
date_format(date_field, "%m%Y") as the_month, 
count(*) 
from 
the_table 
group by 
the_range, the_month 
order by 
the_month, the_range; 

您可以修改查询,以便你显示你的结果,你需要的方式。