SQL查询添加所有客户即使他们没有任何销售

时间:2012-03-23 14:29:24

标签: sql sales

以下是我相对简单的销售查询,但我希望它能够接收我所有的经销商,而不仅仅是有销售的经销商。这可能吗?

SELECT dbo.tblDealer.DealerID, Firstname, LastName,
SUM(dbo.tblOrderDetail.PSVAmount) AS "PSV", 
SUM(dbo.tblOrderDetail.UplineVolume) AS "Upline",
SUM(dbo.tblOrderDetail.LineTotal) AS "Product Total"
FROM tblOrderDetail 
inner join tblOrder 
on dbo.tblOrderDetail.OrderID = dbo.tblOrder.OrderID 
inner join tblDealership on dbo.tblOrder.DealershipID = dbo.tblDealership.DealershipID 
inner join tblDealer on dbo.tblDealership.DealerID = dbo.tblDealer.DealerID
where orderDate between '3/01/12' and '3/21/12 23:59:59'
and dbo.tbldealer.active = -1

GROUP BY dbo.tblDealer.DealerID, Firstname, LastName

1 个答案:

答案 0 :(得分:3)

您应该更改联接的顺序,并执行outer join而不是inner join

SELECT dbo.tblDealer.DealerID, Firstname, LastName,
SUM(dbo.tblOrderDetail.PSVAmount) AS "PSV", 
SUM(dbo.tblOrderDetail.UplineVolume) AS "Upline",
SUM(dbo.tblOrderDetail.LineTotal) AS "Product Total"
FROM tblDealer
inner join tblDealership
on dbo.tblDealership.DealerID = dbo.tblDealer.DealerID
left join tblOrder 
on dbo.tblOrderDetail.OrderID = dbo.tblOrder.OrderID AND orderDate between '3/01/12' and '3/21/12 23:59:59'
left join tblOrder 
on dbo.tblOrderDetail.OrderID = dbo.tblOrder.OrderID 
where dbo.tbldealer.active = -1
GROUP BY dbo.tblDealer.DealerID, Firstname, LastName