Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Error with SUM function using distinct#58101

Unanswered
DavidVaras asked this question inQ&A
Discussion options

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 usesDISTINCT 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 aDISTINCT operation on the amounts and sum them, instead of summing all the amounts across the records.

Real-world example

idProyectoImporte
1P001260
2P0021362
3P0031263
4P0041263
5P0051263
6P0061263
7P00710
8P008 
9P009101
10P010101
   
 Total6886

This query usesDISTINCT, 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
  
Total2996

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)'));

You must be logged in to vote

Replies: 11 comments

Comment options

This is expected behavior. You need to remove:

$elementos->select('reclamacion.*')->distinct();
You must be logged in to vote
0 replies
Comment options

Yeah, if one wants the sum ofall one shouldn't use distinct—why would one anyway in such a case?

You must be logged in to vote
0 replies
Comment options

You can set distinct to false and after sum reset it to the initial value.

You must be logged in to vote
0 replies
Comment options

I need DISTINCT because the original query has many joins, and the query selects many fields.

Thedistinct option should apply to the query itself, but it shouldn't affect theSUM function of that query at all.

The sum function should only perform the sum of the amounts from the result of the original query, not recalculate the records of that query.

If you run a SQL SUM query, it doesn't group by amounts, but by all fields in the query, so in this case it would leave all records.

You must be logged in to vote
0 replies
Comment options

You can set distinct to false and after sum reset it to the initial value.

In that case, there would be more results than I need, because of the joins.

You must be logged in to vote
0 replies
Comment options

This probably isn't a Laravel but an SQL issue. Could you run->ddRawSql() on the query and share the result with us?

You must be logged in to vote
0 replies
Comment options

->ddRawSql()

This is the result of ddRawSql()

select
sum(distinct IFNULL(iva), 0)
)
) as aggregate
from
reclamacion
where
reclamacion.deleted_at is null
andreclamacion.reclamar_a = Instalador
andreclamacion.asignado_empresa in (615, 908, 909)

You must be logged in to vote
0 replies
Comment options

@DavidVaras ddRawSql explains the behavior.
When you call->distinct() on Laravel's query builder, it will be just set on the builder. When you then call->sum(), Laravel's aggregate method generatesSUM(DISTINCT column) as ddRawSql shows.

This is intentional in Laravel.

What you want:SELECT DISTINCT * FROM table then sum
What Laravel does:SELECT SUM(DISTINCT column) which will be sum unique values only

Solution can be what@macropay-solutions mentioned or more readable version which shows what you want first then what you want next.

You must be logged in to vote
0 replies
Comment options

@DavidVaras ddRawSql explains the behavior. When you call->distinct() on Laravel's query builder, it will be just set on the builder. When you then call->sum(), Laravel's aggregate method generatesSUM(DISTINCT column) as ddRawSql shows.

This is intentional in Laravel.

What you want:SELECT DISTINCT * FROM table then sum What Laravel does:SELECT SUM(DISTINCT column) which will be sum unique values only

Solution can be what@macropay-solutions mentioned or more readable version which shows what you want first then what you want next.

If you useget() to sum the amounts in the rows, the result is different than if you use theSUM() function on the same query.

In my humble opinion, you should never useDISTINCT to calculate the total in a sum; it doesn't make sense that if two rows have the same value they aren't summed, much less that this is a generalized calculation method for all the rows in a query.

For the calculation, I'm simply using a foreach loop in PHP.

This ensures that the totaled values ​​match the values ​​returned by the query and those displayed on the screen.

You must be logged in to vote
0 replies
Comment options

@DavidVaras,
You are right, but I think it is better to play with Laravel queries like this by using both get and sum, or any others which provide the expected result:

$total = Model::distinct()    ->get(['column'])    ->sum('column');

Using PHP on the large data, will cause less efficient to loads all rows into memory.

You must be logged in to vote
0 replies
Comment options

Okay, thank you all very much. I thought that was how it was supposed to work.

You must be logged in to vote
0 replies
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
4 participants
@DavidVaras@iazaran@shaedrich@macropay-solutions
Converted from issue

This discussion was converted from issue #58085 on December 12, 2025 11:25.


[8]ページ先頭

©2009-2025 Movatter.jp