【问题标题】:Get information from a MySQL database for a time period given a date从 MySQL 数据库中获取给定日期的一段时间内的信息
【发布时间】:2015-04-02 22:49:46
【问题描述】:

给定一个简单的数据库,例如:

我如何在单个查询中根据他们的开始日期检索员工当年的总销售额?

例如,添加的员工的开始日期为 2015 年 3 月 1 日。2015 年 3 月 1 日至 2016 年 2 月 28 日期间是他们的第一年,而 2016 年 3 月 1 日至 28 日之间的日期是他们的第一年2017 年 2 月是第二年,以此类推。

因此,如果在 2017 年 3 月 5 日运行查询,它将返回 2017 年 3 月 1 日至 2017 年 3 月 5 日之间的数据,因为那是当前年份。同样,如果查询在 2017 年 2 月 13 日运行,它将返回 2016 年 3 月 1 日至 2017 年 2 月 13 日之间的所有销售额,因为那将是他们当前的年份。

目前,我可以完成这项工作的唯一方法是在一个查询中检索员工的开始日期,从一年中获取月份和日期,检查日期是否已经过了今年,然后形成新的一年以这种方式开始日期。比如这样:

//Get the year start date for the employee
$stmt = $dbh->prepare("select StartDate from employee where EmpID = ?");
$stmt->execute(array($empID));
$employee = $stmt->fetch(PDO::FETCH_ASSOC);
$dateArray = explode("-", $employee['StartDate']);

//If the current month and day is greater than the start date then its not been the end of the year, so the start year is the current year -1
//If not then it has not gone past the end of the year, and the start year is same as the current year.

if (date('m') <= $dateArray[1] && date('d') <= $dateArray[2]){
    $yearStart = (date('Y')-1)."-".$dateArray[1]."-".$dateArray[2];
}else{
    $yearStart = date('Y')."-".$dateArray[1]."-".$dateArray[2];
}

然后我可以再次查询数据库以从生成的年份开始检索所有销售额。

以上方法可行,但是否有可能将其放入单个 MySQL 查询中?

【问题讨论】:

  • SELECT DATE_ADD(StartDate , INTERVAL 365 DAY)as YearCompleteDate fromemployee where EmpID=?;将为您提供结束日期。

标签: mysql sql


【解决方案1】:

这是一个有点复杂的日期算术。您需要将销售日期的月/日与开始日期的月/日进行比较。然后,您需要确定年份是当前年份还是上一年。

下面表达了这个逻辑,假设销售日期不在未来:

select e.empId, count(*), sum(amount)
from employee e join
     sales s
     on e.empId = s.empId
where (date_format(now(), '%m-%d') >= date_format(e.startdate, '%m-%d') and
       s.date >= str_to_date(concat_ws('-', year(now()), month(e.startdate), day(e.startdate))
      ) or
      (date_format(now(), '%m-%d') < date_format(e.startdate, '%m-%d')
       s.date >= str_to_date(concat_ws('-', year(now()) - 1, month(e.startdate), day(e.startdate))
      )
group by e.empId

【讨论】:

    猜你喜欢
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 2019-11-07
    • 2011-05-30
    • 1970-01-01
    • 2015-09-04
    • 2014-07-19
    相关资源
    最近更新 更多