Question

I am running a SBS 2008 with SQL Server 2008 R2

MYOB EXONET SQL Database

I am trying to find out how much our top customers are spending per month but the below query will not return a zero value if the customer has not spent, I imagine that it does not give me a zero result as there is nothing to add up in the database, however I still need it to produce a zero result as otherwise I can't find out which customers are not spending.

SELECT 
    DR.ACCNO, 
    SUM(Analytics_SaleInvoice.SalesValueTaxExclusive)
FROM 
    DR_ACCS DR 
INNER JOIN 
    Analytics_SaleInvoice Analytics_SaleInvoice ON (Analytics_SaleInvoice.AccountNumberAnalysis = DR.ACCNO)
WHERE 
    (DR.X_TOPCUSTOMER = 'Y')
    AND (Analytics_SaleInvoice.AgePeriod = 5) 
GROUP BY 
    DR.ACCNO, DR.ACCNO,Analytics_SaleInvoice.AccountNumberAnalysis 

Does anyone have any idea how I can get a zero result?

Was it helpful?

Solution

You need left outer join so you get all customers:

SELECT DR.ACCNO,
       COALESCE(SUM(Analytics_SaleInvoice.SalesValueTaxExclusive), 0) as Total
FROM DR_ACCS DR LEFT OUTER JOIN
     Analytics_SaleInvoice Analytics_SaleInvoice  
     ON Analytics_SaleInvoice.AccountNumberAnalysis = DR.ACCNO AND
        Analytics_SaleInvoice.AgePeriod = 5
WHERE DR.X_TOPCUSTOMER = 'Y' 
GROUP BY DR.ACCNO, DR.ACCNO,Analytics_SaleInvoice.AccountNumberAnalysis
ORDER BY COALESCE(SUM(Analytics_SaleInvoice.SalesValueTaxExclusive), 0) DESC;

Along with the left outer join, the condition on the second table needs to be moved to the on clause and the coalesce() is used to turn the NULL value into a 0.

I also added an order by because you seem to want the best customers first.

OTHER TIPS

Use a LEFT JOIN between DR_ACCS and Analytics_SalesInvoice instead of an INNER JOIN. A LEFT JOIN is guaranteed to at least return one result for each record in DR_ACCS. Something like this should work:

SELECT DR.ACCNO, IsNull( SUM(Analytics_SaleInvoice.SalesValueTaxExclusive), 0)
FROM DR_ACCS DR LEFT JOIN Analytics_SaleInvoice Analytics_SaleInvoice  
ON (Analytics_SaleInvoice.AccountNumberAnalysis = DR.ACCNO)
WHERE (DR.X_TOPCUSTOMER = 'Y')
AND ( (Analytics_SaleInvoice.AgePeriod = 5)  OR (Analytics_SalesInvoice.AgePeriod IS NULL) )
GROUP BY DR.ACCNO, DR.ACCNO,Analytics_SaleInvoice.AccountNumberAnalysis 

Try a LEFT JOIN instead:

SELECT 
    DR.ACCNO, 
    ISNULL(SUM(Analytics_SaleInvoice.SalesValueTaxExclusive), 0)
FROM DR_ACCS DR 
LEFT JOIN Analytics_SaleInvoice Analytics_SaleInvoice  
    ON (Analytics_SaleInvoice.AccountNumberAnalysis = DR.ACCNO)
    AND (Analytics_SaleInvoice.AgePeriod = 5) 
WHERE (DR.X_TOPCUSTOMER = 'Y')
GROUP BY DR.ACCNO, DR.ACCNO,Analytics_SaleInvoice.AccountNumberAnalysis 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top