Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SUM + Distinct

Tags:

sql

mysql

I want to know the request with which I displayed the sum of the amounts of the various clients that do not repeat with the SUM function and DISTINCT.

I used :

SELECT DISTINCT id_721z, SUM(montant) AS somme_montant 
FROM `roue_ventes_cb` 
WHERE `date_transaction` between '2015/01/01' and '2015/01/21';

But the result is not displayed correctly. I have this data:

id_721z | montant

1   |   15
1   |   15
2   |   22
2   |   22
2   |   22

I would like to show total_montant = 37 but not

id_721z | montant

1   |   30
2   |   66
like image 213
Ayed Mohamed Amine Avatar asked Feb 27 '26 09:02

Ayed Mohamed Amine


2 Answers

SELECT SUM(montant) AS somme_montant
FROM (
    SELECT DISTINCT id_721z, montant
    FROM `roue_ventes_cb`
    WHERE `date_transaction` between '2015/01/01' and '2015/01/21'
) AS t
like image 132
eumiro Avatar answered Mar 01 '26 16:03

eumiro


This will sum all different montants. But if two ids have the same montant it will only count it once.

SELECT id_721z, SUM(DISTINCT montant) AS somme_montant 
FROM `roue_ventes_cb` 
WHERE `date_transaction` between '2015/01/01' and '2015/01/21';

So I will prefer emiros answer in any case. It is safer and distint will have a performance penalty anyway.

like image 42
borjab Avatar answered Mar 01 '26 17:03

borjab