簡體   English   中英

在兩個日期之間搜索並按月排序

[英]Search between two dates and sort by months

我是新來的兩個日期之間的搜索記錄,並顯示按月排序的記錄(從一月到十二月)。

我有這樣的桌子。

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' 

請給我一個解決問題的想法。

您需要數據透視表,不幸的是,在mysql中數據透視表是靜態的,因此您需要針對每種情況編寫它(但是您可以使用腳本來完成此操作),但下面有一個僅用於示例數據的示例,但可以繼續進行。

嘗試這個:

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

使用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 ║
╚════════════╩═══════════════════╩══════════════════╝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM