在两个日期之间搜索并按月排序

时间:2013-06-27 07:14:47

标签: php mysql date

我是新的两个日期之间的搜索记录,并显示按月(从1月到12月)排序的记录。

我有这样的表格。

Employee  |  Salary  |  Date from  |  Date To  
John A.   |   15000  | 2013-05-26  |  2013-06-10  
Mark      |   15000  | 2013-05-26  |  2013-06-10  
John A.   |   15000  | 2013-06-11  |  2013-06-25 
Mark      |   20000  | 2013-06-11  |  2013-06-25  

我希望报告显示如下。

Employee  |   26 May - June 10   |  11 June - 25 June   | So on..  
John A.   |          15000       |         15000 
Mark      |          15000       |         20000          

请查看我的密码。这只会搜索两个日期之间的记录

SELECT * 
FROM payroll
WHERE datefrom >= '2013-01-01' 
AND dateto < '2013-12-31' 

请告诉我如何解决问题。

2 个答案:

答案 0 :(得分:0)

你需要转动数据,不幸的是在mysql中,pivot是静态的,所以你需要为每个案例编写它(但你可以用脚本来编写),下面你有一个样本只是为了样本数据,但它可以待续。

试试这个:

SELECT  
    employee,
    SUM(IF(datefrom='2013-05-26' AND dateto='2013-06-10',Salary,0)) as `26 May - June 10`,
    SUM(IF(datefrom='2013-06-11' AND dateto='2013-06-25',Salary,0)) as `11 June - 25 June`
FROM 
    payroll
WHERE 
    datefrom >= '2013-01-01' 
    AND dateto < '2013-12-31' 
GROUP BY
    employee

答案 1 :(得分:0)

尝试使用php

  <?php

// connection
$dns = "mysql:host=localhost;dbname=***";
$dbh = new PDO($dns, 'user', '***');

// sql
$query = "SELECT DISTINCT (CONCAT(`datefrom` ,' ', `dateto` )) as `formated date`
          FROM empdetail";

$stmt   = $dbh->prepare($query);
$stmt->execute();

$case_string = '';

while($r = $stmt->fetch(PDO::FETCH_ASSOC))
{
   list($fromdate,$todate) = explode(' ',$r['formated date']);
   $from                   = date('d-M',strtotime($fromdate));
   $to                     = date('d-M',strtotime($todate));
   $case_string.= "SUM(IF(datefrom='{$fromdate}' AND dateto='{$todate}',Salary,0)) as `{$from} to {$to}`,";

}

$case_string  = rtrim($case_string,',');


$sql = "SELECT employee, {$case_string}
        FROM empdetail 
        GROUP BY employee";

$stmt1 = $dbh->prepare($sql);
$stmt1->execute();
while($r = $stmt1->fetch(PDO::FETCH_ASSOC))
{
   // do whatever you want
}
?>

在PHYMYADMIN中运行最终SQL时的输出

╔════════════╦═══════════════════╦══════════════════╗
║  employee  ║ 26-May to 10-Jun  ║ 11-Jun to 25-Jun ║
╠════════════╬═══════════════════╬══════════════════╣
║ john       ║            15000  ║            15000 ║
║ Mark       ║            15000  ║            20000 ║
╚════════════╩═══════════════════╩══════════════════╝