php - 在 MySQL 中通过单个查询获取今天、本周、本月和今年的数据?

标签 php mysql sql date-range

我正在从数据库中检索今天的数据,我想检索本月,今年的数据,是否可以在单个查询中进行?或者我应该对每个项目进行单独的查询? 我的查询如下,

    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)

最佳答案

使用条件聚合:

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

关于php - 在 MySQL 中通过单个查询获取今天、本周、本月和今年的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30139980/

相关文章:

php - 在 div 不回显 php 之后

php - 为什么 is_array() 在 PHP 中会泄漏内存?

mysql - MySQL 变量中的多个值

mysql - SQL不存在发现一些问题

mysql - 如何执行多列透视

php - ajax 无法连接 mysqli?

php - 使用现有标记渲染 Zend_Form 的最佳方法

mysql - FullCalendar jquery json 事件 MySQL 问题

Java 类路径找不到 MySQL 驱动程序

java - 从 SQL 脚本生成带有 JPA 注释的 Java 类