首页 文章

在给定日期的时间段内从MySQL数据库获取信息

提问于
浏览
0

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

database

如何在一个查询中查看员工在当前年份的总销售数量?

例如,员工的开始日期为2015年3月1日 . 2015年3月1日至2016年2月28日为第一年,2016年3月1日至2017年2月28日为止是第二年等

因此,如果查询在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查询吗?

1 回答

  • 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
    

相关问题