如何通过未保存在数据库中的字段对查询结果进行分组。
例如,我想按照开始时间和结束时间减去的持续时间对结果进行分组。
这是我如何找出持续时间
date1= $row_TicketRS['CloseDate'];
$date2 = $row_TicketRS['OpenDate'];
$diff = abs(strtotime($date2) - strtotime($date1));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
if ( $days > 0)
{
$time1 = $row_TicketRS['OpenTime'];
$time2= $row_TicketRS['CloseTime'];
$t1=($time1);
$t2=($time2);
$end=('14:30');
$start=('07:30');
$n = $end- $t1;
$n2 = $t2- $start;
$Hours2 = floor(($n+$n2)+(($days-1)*7));
echo $Hours2.' Hours';
但知道我不知道如何将其添加到查询
这是我的查询
$strQuery = "SELECT count(`ticket`.TicketID) as TotOutput, department.`DeptName` FROM `ticket`, `user`, department where ticket.OwnerID = user.EmpNo and user.`DepartmentID` = department.`DepartmentID` and OpenDate between'".$DateFrom."' And '".$DateTo."'"
答案 0 :(得分:2)
最好有详细信息,但派生表/内联视图允许您按计算值进行分组:
SELECT x.duration,
COUNT(*)
FROM (SELECT t.col,
t.end_time - t.start_time AS duration
FROM YOUR_TABLE t) x
GROUP BY x.duration
答案 1 :(得分:0)
如何使用如下别名将该计算值添加到查询中:
SELECT some_fields, end - start AS duration FROM table ORDER BY duration
答案 2 :(得分:0)
不要为隐藏列添加别名,直接使用
〔实施例:
SELECT id, FLOOR(value/100)
FROM tbl_name
GROUP BY id, FLOOR(value/100);
MySQL允许GROUP BY中的表达式 条款,所以别名是不必要的: