[英]Get today,this week,this month and this year data in single query in MySQL?
I am retrieving today's data from db,I want to retrieve this month,this year data as well,Is it possible in single query? 我正在从db检索今天的数据,我也想检索本月,今年的数据,是否可以在单个查询中? or should I go with separate query for each items?
还是应该为每个项目单独查询? My query given below,
我的查询如下
select sum(it.rate * it.quantity)as sales from invoices i
join invoice_items it on i.id = it.invoice_id
where i.invoice_date > DATE_SUB(NOW(), INTERVAL 1 DAY)
Use conditional aggregation: 使用条件聚合:
select sum(case when i.invoice_date > DATE_SUB(NOW(), INTERVAL 1 DAY) then it.rate * it.quantity
end) as sales_1day,
sum(case when i.invoice_date > DATE_SUB(NOW(), INTERVAL 7 DAY) then it.rate * it.quantity
end) as sales_7day,
sum(case when i.invoice_date > DATE_SUB(NOW(), INTERVAL 1 MONTH) then it.rate * it.quantity
end) as sales_1month,
sum(case when i.invoice_date > DATE_SUB(NOW(), INTERVAL 1 YEAR) then it.rate * it.quantity
end) as sales_1year
from invoices i join
invoice_items it
on i.id = it.invoice_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.