Skip to content

Error with SUM function using distinct #58085

@DavidVaras

Description

@DavidVaras

Laravel Version

12.8.1

PHP Version

8.3.28

Database Driver & Version

mysql Ver 8.0.32 for Linux on x86_64 (MySQL Community Server - GPL)

Description

If your query uses DISTINCT and you want to find the sum of a field, such as an amount, when you execute the function $elementos->sum('importe'), it will perform a DISTINCT operation on the amounts and sum them, instead of summing all the amounts across the records.

Real-world example

id Proyecto Importe
1 P001 260
2 P002 1362
3 P003 1263
4 P004 1263
5 P005 1263
6 P006 1263
7 P007 10
8 P008  
9 P009 101
10 P010 101
     
  Total 6886

This query uses DISTINCT, and the result is shown above. If you run $elementos->sum(DB::raw('IFNULL(importe,0)'));

A filter is applied to the different amounts in the result; it doesn't use all the rows displayed. This means that when you have identical amounts, only one of them is summed.

The result of that instruction would be:

  Importe
  260
  1362
  1263
  10
  101
   
Total 2996

From my point of view it is a mistake because when you ask for the sum of the records you want the total sum and not just the different ones.

Thanks in advance.

Steps To Reproduce

Create an Eloquent query with multiple fields, using the DISTINCT clause in the SELECT clause, and one of the fields being an amount field. There must be multiple amounts with the same value within the selected records.

$elementos = Reclamacion::whereNull('reclamacion.deleted_at');
$elementos->select('reclamacion.*')->distinct();
$elementos->sum(DB::raw('IFNULL(importe,0)'));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions