【发布时间】: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=?;将为您提供结束日期。