如何在没有销售的情况下显示客户(结果)

时间:2017-08-25 13:47:42

标签: sql

我有一个代码可以吸引所有Reps新客户及其年初至今的销售额。唯一的问题是它只会拉动在invdate范围内销售的客户,但如果他们没有任何销售,我需要它显示所有帐户的0。有没有办法实现这个目标?我尝试使用COALESCE,它似乎不起作用。我也试过使用左,右,全外连接。任何帮助将不胜感激!

select 
a.Acctnum,  
sum(a.invtotal) as total 
from invoices a right join accounts b on a.acctnum = b.acctnum where 
a.invdate between '1/1/2017' and '12/31/2017'
and a.sls = '78'
and b.sls = '78'
and b.activetype = 'y' and b.startdate > (getdate()-365)
group by a.acctnum
order by total desc

2 个答案:

答案 0 :(得分:2)

您在WHERE子句中限制结果 AFTER 您加入表会导致记录丢失。相反,切换到LEFT OUTER JOINaccounts表驱动查询。然后限制invoices子句中的ON表格,以便在加入之前>

invoices

在加入左表之前,有点像在SELECT a.Acctnum, sum(a.invtotal) AS total FROM accounts b LEFT OUTER JOIN invoices a ON a.accntnum = b.acctnum AND --Put the restrictions on your left most table here --so they are removed BEFORE joining. a.invdate BETWEEN '1/1/2017' AND '12/31/2017' AND a.sls = '78' WHERE b.sls = '78' AND b.activetype = 'y' AND b.startdate > (getdate() - 365) GROUP BY a.acctnum ORDER BY total DESC 中做一个子查询。将条件放入invoices子句更容易。

答案 1 :(得分:0)

您的问题在于哪些子句正在将右连接更改为内连接。把所有别名的东西放在一个。进入ON条款。