Php 在两个日期之间搜索并按月份排序
我是新的,搜索记录介于两个日期之间,并显示按月份排序的记录(从1月到12月) 我有这样的桌子Php 在两个日期之间搜索并按月份排序,php,mysql,date,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 Mar
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
我希望报告能像这样显示出来
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'
选择*
来自工资单
其中datefrom>=“2013-01-01”
日期<'2013-12-31'
请告诉我如何解决这种情况。您需要ti pivot数据,不幸的是在mysql中pivot是静态的,因此您需要为每种情况编写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
选择
雇员,,
金额(如果(日期为2013年5月26日至2013年6月10日,工资为0))为“5月26日至6月10日”,
金额(如果(日期从2013年6月11日至2013年6月25日,工资为0))为“6月11日至6月25日`
从…起
工资名单
哪里
日期自>='2013-01-01'
日期<'2013-12-31'
分组
雇员
尝试使用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
}
?>
分组的基础是什么?您正在寻找的称为数据透视表。看看我唯一的问题是对月份的排序@让我们将此分组编码为我的年度记录摘要。您的意思是使用SQL实际排序或将日期周期显示为列吗?您的示例输出和评论令人困惑。很抱歉给您带来困惑@peterm让我们总结一下,我需要按日期筛选工资记录,假设从1月到12月,我希望这些记录显示为从1月到12月排序。@Jason。。很高兴帮助你。。如果您觉得这个答案有帮助,请随意接受:)