查询以获取雇员列值

时间:2018-09-11 10:56:17

标签: php mysql mysqli

我正在跟踪表订单中的所有员工数据。...

我需要提取所有员工[列名:雇员姓名]重新尝试[列: reattemptdate ]和保留值[列: holddat e ]

我想以以下格式显示该信息:

员工姓名1:重新尝试:重新尝试值:保留:保留值

员工姓名2:重新尝试:重新尝试值:保留:保留值

示例

chittaranjan:反击:20,保持:10

Deepak Reattempet:15,保持:5

我在下面的查询中尝试过:

$sql = "SELECT employeename, DATE(reattemptdate) as date, 
COUNT(*) as count, 0 as Held FROM orders 
WHERE DATE(reattemptdate)  = CURDATE() 
GROUP BY employeename, date

UNION

SELECT employeename, DATE(holddate) as date, 
COUNT(*) as count, 1 as Held  FROM orders 
WHERE DATE(holddate)  = CURDATE() 
GROUP BY employeename, date
"; 
$results = $db_handle->runSelectQuery($sql); 
$numrowsresult =$results[0]['count'];

foreach ($results as $result) 
{
    if ($result['Held']==0){
      $header = " Reattempet ";
    } else {
      $header = " hold ";
    }
    echo $result['employeename']."<br>";
    echo $header.": ".$result['count']."<br>";
}

我得到的输出如下:

chittaranjan Reattempet:20

deepak Reattempet:15

chittaranjan要塞:10

深潜保持力:5

我需要对上述查询进行哪些更改才能获得所需的结果。...

编辑-列结构

enter image description here

按住

enter image description here

示例

enter image description here

2 个答案:

答案 0 :(得分:1)

另一种方法是修改代码:

foreach ($results as $result) 
{
  if ($result['Held']==0){
    $new_array[$result['employeename']][0] = " Reattempet :" . $result['count'];
  } else {
    $new_array[$result['employeename']][1] = " hold :" . $result['count'];
  }
}
foreach ($new_aray as $name => $val)
{
  echo $name . " : " . $val[0] . " : " . $val[1];
}

答案 1 :(得分:1)

让数据库来完成这项工作,它是为它量身定制的

将查询更改为此:

SELECT CONCAT(employeename,' : Reattempt : ', count_Reattempet, ' : Hold : ', count_Hold) AS concat_header
FROM
(
    SELECT employeename, 
           SUM(CASE WHEN Held = 'Reattempet' THEN 1 ELSE 0 END) AS count_Reattempet,
           SUM(CASE WHEN Held = 'Hold'       THEN 1 ELSE 0 END) AS count_Hold
    FROM
    (
        SELECT employeename, DATE(reattemptdate) as date, 'Reattempet' as Held FROM orders WHERE DATE(reattemptdate)  = CURDATE() 
        UNION
        SELECT employeename, DATE(holddate)      as date, 'Hold'       as Held  FROM orders WHERE DATE(holddate)  = CURDATE() 
    ) A
    GROUP BY employeename
) B

它将返回一列concat_header,其格式完全符合您的要求。

chittaranjan : Reattempet : 20 : hold : 10
Deepak Reattempet : 15 : hold : 5

然后您只需要用PHP来完成

foreach ($results as $result) 
{
      echo $result['concat_header']."<br>";
}