简体   繁体   中英

MYSQL Distinct values with totals

Trying to return a list of all of my users that have resolved a ticket and the number of tickets they resolved. This code works , but it seems bad practice to query inside of a while loop.

Is there a more efficient way?

//Get all users who have resolved a ticket
$stmt = $db->prepare("SELECT DISTINCT resolvedby FROM tickets");
$stmt->execute();

while($rows = $stmt->fetch()){
    $user = $rows['resolvedby'];
    echo "$user "; //Echo each user

    $new = $db->prepare("SELECT count(resolvedby) as total FROM tickets WHERE resolvedby = :u ");
    $new->bindParam('u',$user);
    $new->execute();

    $row = $new->fetch();
    echo $row['total']; //Echo the total of each user
    echo "<br />";
}

Returns:

User    Total Resolved
Shawn        40
David        38
Jeff         52
Frank        47

You need to use group by with aggregate function count:

SELECT
      resolvedby
    , COUNT(*) AS total
FROM
    tickets
GROUP BY
    resolvedby

Sure, you'd like to limit results with some WHERE clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM