What are the best practices for handling team-based data calculations in PHP when working with SQL queries?

When handling team-based data calculations in PHP with SQL queries, it is best to use SQL functions and clauses to perform the calculations directly in the database query rather than fetching all the data and processing it in PHP. This approach reduces the amount of data transferred between the database and PHP, improving performance and scalability.

// Example of calculating the total sales amount for a team using SQL query
$query = "SELECT team_id, SUM(sales_amount) AS total_sales
          FROM sales_data
          WHERE team_id = :team_id
          GROUP BY team_id";

$stmt = $pdo->prepare($query);
$stmt->bindParam(':team_id', $team_id);
$stmt->execute();

$result = $stmt->fetch(PDO::FETCH_ASSOC);

$total_sales = $result['total_sales'];