lkartono
lkartono

Reputation: 2393

MySQL sum return 0 by default

I have an issue using the sum functionnality. So basically, I have 2 tables, paiment_type and bills. In the bills table, I have a foreign key name fk_paiement_type which allow me to know what kind of paiement was used for this particular bills.

When printing statistics, I'm doing this to get the total by paiement type :

SELECT 
  pt.name,
  SUM(f.total_ttc) AS total_mode 
FROM
  bills AS f 
  INNER JOIN paiement_type AS pt 
    ON pt.id = f.fk_paiement_type 
WHERE (
    f.created BETWEEN '2013-01-10' 
    AND '2013-01-10'
  ) 
  AND (
    f.type LIKE 'facture' 
    OR f.type LIKE ''
  ) 
GROUP BY f.fk_paiement_type 

This code works well but I have actually 3 differents paiement type and sometimes only 2 of them were used during the day and I still want to display it same if it does not exists.

EDIT : I already tried to use IFNULL functionnality but it didn't work. The fk_paiement_type from the bills table will sometimes return only 2 values who match the paiement_type table. I think my problem come from here :

INNER JOIN paiement_type AS pt ON pt.id = f.fk_paiement_type 

Any idea?

EDIT2 :

My table structure are as follow :

**Bills Table**

id (int), 
fk_paiement_type (int), 
ref (varchar), 
fk_client (int), 
tss (double), 
total_ttc (double), 
type (varchar), 
created (datetime)

**Paiement_type Table**

id (int), 
name (varchar)

I tried your last answer but it still didn't work. For now, I just bypass this issue in my Java code but I would love to have a "clean" way to do it.

Thanks a lot for your help

Upvotes: 4

Views: 1573

Answers (2)

echo_Me
echo_Me

Reputation: 37233

try this

   SELECT 
    f.thename,
     f.total_mode 
    FROM (SELECT name as thename , SUM(total_ttc) AS total_mode  from bills 
          WHERE (
           f.created BETWEEN '2013-01-10' 
           AND '2013-01-10'
          ) 
           AND (
                f.type LIKE 'facture' 
             OR f.type LIKE ''
               ) GROUP BY fk_paiement_type  ) f
    INNER JOIN paiement_type AS pt 
    ON pt.id = f.fk_paiement_type 

Upvotes: 0

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

Here it is use ifnull

SELECT 
  pt.name,
  IFNULL(SUM(f.total_ttc),0) AS total_mode 
FROM
  factures AS f 
  INNER JOIN paiement_type AS pt 
    ON pt.id = f.fk_paiement_type 
WHERE (
    f.created BETWEEN '2013-01-10' 
    AND '2013-01-10'
  ) 
  AND (
    f.type LIKE 'facture' 
    OR f.type LIKE ''
  ) 
GROUP BY f.fk_paiement_type 

Edit :

SELECT 
  pt.name,
  SUM(f.total_ttc) AS total_mode 
FROM
  bills AS f 
INNER JOIN (SELECT * FROM paiement_type GROUP BY fk_paiement_type) AS pt ON pt.id = f.fk_paiement_type 
WHERE (f.created BETWEEN '2013-01-10' AND '2013-01-10') AND (f.type LIKE 'facture' OR f.type LIKE '') 
GROUP BY f.fk_paiement_type 

I think multiple results are joined when you are using inner join so restrict inner join to fetch only 1 record per group

Upvotes: 7

Related Questions