具有相同分组的多个计数查询

时间:2016-07-27 09:12:25

标签: php mysql

我试图在查询中检索具有不同WHERE的不同值的计数,但是将它们全部按相同的值分组。

我尝试了以下示例:

$sql = "SELECT * FROM (  SELECT COUNT(id) AS mail FROM leadz WHERE source = 'mail' UNION ALL
                 SELECT COUNT(id) AS phone FROM leadz WHERE source = 'phone' UNION ALL
                 SELECT COUNT(id) AS direct  FROM leadz WHERE source = 'direct' UNION ALL 
                 SELECT COUNT(id) AS external FROM leadz WHERE source = 'external' 
                       ) GROUP BY date";

然后我尝试使用以下方法访问数据:

 $query = mysqli_query($con,$sql);
 while($row = mysqli_fetch_assoc($query)){
    echo "in date ".$row['date'].": ".$row['mail'].",".$row['phone'].",".$row['direct'].",".$row['external']."<br>";

这显然不起作用。任何人都很感激。

2 个答案:

答案 0 :(得分:0)

这样的事情应该有效:

SELECT date, source, COUNT(id) AS how_many
FROM leadz 
WHERE source IN ('mail', 'phone', 'direct', 'external')
GROUP BY date, source
ORDER BY date

临时数组可用于将行放在列中:

$tmp = array();

$query = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($query))
    $tmp[$row['date']][$row['source']] = $row['how_many'];

foreach ($tmp as $date => $source)
    echo 'in date ' . $date . ': ' . $source['mail'] . ',' . $source['phone'] . ',' . $source['direct'] . ',' . $source['external'] . '<br>' . "\r\n";

答案 1 :(得分:0)

您可以尝试使用带有总和的CASE语句而不是单独的子查询:

原始代码:

$sql = "SELECT * FROM (  SELECT COUNT(id) AS mail FROM leadz WHERE source = 'mail' UNION ALL
             SELECT COUNT(id) AS phone FROM leadz WHERE source = 'phone' UNION ALL
             SELECT COUNT(id) AS direct  FROM leadz WHERE source = 'direct' UNION ALL 
             SELECT COUNT(id) AS external FROM leadz WHERE source = 'external' 
                   ) GROUP BY date";

使用条件总和更新:

$sql = "SELECT
l.DATE
,SUM(CASE WHEN l.SOURCE = 'mail' THEN 1 ELSE 0 END) AS SOURCE_MAIL
,SUM(CASE WHEN l.SOURCE = 'phone' THEN 1 ELSE 0 END) AS SOURCE_PHONE
,SUM(CASE WHEN l.SOURCE = 'direct' THEN 1 ELSE 0 END) AS SOURCE_DIRECT
,SUM(CASE WHEN l.SOURCE = 'external' THEN 1 ELSE 0 END) AS SOURCE_EXTERNAL
FROM LEADZ AS l
GROUP BY l.DATE";

然后要访问php中的输出,您可以使用以下内容:

$result = mysqli_query($link,$sql);
while($r = mysqli_fetch_array($result)) {
extract($r);
echo $DATE.'<BR>'.
'mail: '$SOURCE_MAIL.'<BR>'.
'phone: '$SOURCE_PHONE.'<BR>'.
'direct: '$SOURCE_DIRECT.'<BR>'.
'external: '$SOURCE_EXTERNAL.'<BR><hr>';
}