[英]Mysql Group by specific time intervals
無論如何有沒有按特定時間間隔分組的示例,例如,我有這種類型的表:
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
但這是行不通的,是否有按指定的日期間隔返回結果?
您可以使用條件聚合來做到這一點:
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`
您可以使用功能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合計invoice_balance,請使用以下命令:
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
如果您需要按期總計invoice_balance,請使用以下命令:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.