我正在运行带有SQL Server 2008 R2的SBS 2008
MYOB EXONET SQL数据库
我试图了解我们的顶级客户每月花费多少,但如果客户没有花费,下面的查询将不会返回零值,我想它没有给我零结果,因为没有什么要在数据库中加起来,但是我仍然需要它来产生零结果,否则我无法找出哪些客户没有消费。
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
有谁知道我怎么能得到零结果?
答案 0 :(得分:0)
尝试使用LEFT JOIN
:
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
答案 1 :(得分:0)
您需要left outer join
才能获得所有客户:
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;
与left outer join
一起,第二个表格中的条件需要移至on
子句,而coalesce()
用于将NULL
值转换为0
。
我还添加了order by
,因为您似乎首先想要最好的客户。
答案 2 :(得分:0)
在DR_ACCS和Analytics_SalesInvoice之间使用LEFT JOIN而不是INNER JOIN。 LEFT JOIN保证至少为DR_ACCS中的每条记录返回一个结果。这样的事情应该有效:
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