在计算mysql union查询时显示不同的文本

问题描述 投票:0回答:1

我使用下面的代码来获得2列的数量 - Reattemptdate&Holddate

<?php
$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) 
{
    echo "Reattempt : ".$result['count']."<br>";
}

我得到的结果如下,在前6个值来自reattemptdate列,接下来6个来自holddate列,如何显示文本Hold而不是Reattempt在下面的图像中的最后6行:

enter image description here

php
1个回答
2
投票

您可以根据“已保留”列使用逻辑:例如:

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

或者在结果集中添加一个显式标题,如下所示:

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

UNION

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

foreach ($results as $result) 
{
    echo $result['header'].": ".$result['count']."<br>";
}
© www.soinside.com 2019 - 2024. All rights reserved.