MySQL组按特定时间间隔

时间:2019-07-02 05:37:56

标签: mysql database group-by

例如,是否有按特定时间间隔分组的表格,我有这种类型的表:

invoice_id  due_date    invoice_balance
4           2019-02-04  192
5           2019-03-18  0   
6           2019-03-18  3
7           2019-04-24  30392   
8           2019-04-25  47.5    

现在我有很多这样的记录,我希望它们按特定的日期间隔进行分组( 今天,今天+7天,7天至30天,超过30天),总金额为:

预期结果:

total  date between
2000   today
2000   today+7 day
2000   7dayto30day
2000   morethan30days

所以我尝试了这样的事情:

SELECT SUM(invoice_balance) as sum,invoice_id, due_date 
FROM `my_invoice_master` 
GROUP BY if(due_date between "2019-02-04" and "2019-04-26",0,1),if(due_date between "2019-07-05" and "2019-07-09",0,1) 
ORDER BY u.meta_value asc LIMIT 0 , 10

但是它不起作用,是否仍要以指定的日期间隔返回结果?

2 个答案:

答案 0 :(得分:1)

您可以通过条件聚合来做到这一点:

SELECT 
  SUM(case 
        when due_date = current_date then invoice_balance 
        else 0 
      end) as `today`,
  SUM(case 
        when due_date between current_date + interval 1 day and current_date + interval 7 day then invoice_balance 
        else 0 
      end) as `today+7 day`,
  SUM(case 
        when due_date between current_date + interval 8 day and current_date + interval 30 day then invoice_balance 
        else 0 
      end) as `7dayto30day`,  
  SUM(case 
        when due_date > current_date + interval 30 day then invoice_balance 
        else 0 
      end) as `morethan30days`
FROM `my_invoice_master` 

答案 1 :(得分:0)

您可以使用功能IF:

select invoice_id, invoice_balance, 
  IF(DATEDIFF(DATE(due_date), DATE(NOW()))<=7
    , IF(DATEDIFF(DATE(due_date), DATE(NOW()))>0, 'today+7', 'today')
    , IF(DATEDIFF(DATE(due_date), DATE(NOW()))<=30, '7dayto30day', 'morethan30days')
  ) as due_period
from my_invoice_master

此查询按时段显示所有记录。如果Due_date会小于今天,那么它将使您“今天”。


如果您需要按 invoice_id 的总帐款余额,请使用以下方法:

select invoice_id, sum(invoice_balance), 
  @due_period:= IF(DATEDIFF(DATE(due_date), DATE(NOW()))<=7
    , IF(DATEDIFF(DATE(due_date), DATE(NOW()))>0, 'today+7', 'today')
    , IF(DATEDIFF(DATE(due_date), DATE(NOW()))<=30, '7dayto30day', 'morethan30days')
  ) as due_period
from my_invoice_master
group by invoice_id, @due_period

如果您需要按期支付发票余额,请使用以下方法:

select sum(invoice_balance), 
  @due_period:= IF(DATEDIFF(DATE(due_date), DATE(NOW()))<=7
    , IF(DATEDIFF(DATE(due_date), DATE(NOW()))>0, 'today+7', 'today')
    , IF(DATEDIFF(DATE(due_date), DATE(NOW()))<=30, '7dayto30day', 'morethan30days')
  ) as due_period
from my_invoice_master
group by @due_period