客户表共有1000个客户,其中2016年有1500个订单。但我们希望在2016财年显示所有客户的订单总数,无论客户是否在该风险中下订单。但SQL Server 2012中的以下查询仅显示1490.
我们在这里可能缺少什么?
SELECT c.CustomerID, count(*) AS TotalOrders
FROM Customers c
LEFT JOIN Orders o ON c.CustomerID = o.CustomerID
WHERE o.FiscalYear = '2016'
GROUP BY c.CustomerID
更新:
以下查询仅返回1条记录(1491) - 仍然缺少9条记录。
SELECT c.CustomerID, count(*) AS TotalOrders
FROM Customers c
LEFT JOIN Orders o ON c.CustomerID = o.CustomerID
AND o.FiscalYear = '2016'
GROUP BY c.CustomerID
答案 0 :(得分:6)
您where
子句正在将left outer join
变为Inner join
。
将其更改为AND
:
SELECT c.CustomerID, count(o.CustomerID) AS TotalOrders
FROM Customers c
LEFT JOIN Orders o
ON c.CustomerID = o.CustomerID
AND o.FiscalYear = '2016' -- Here
GROUP BY c.CustomerID
答案 1 :(得分:0)
正确的SQL是:
SELECT c.CustomerID, count(o.CustomerID) AS TotalOrders,
sum(count(o.CustomerID)) over () as TotalTotalOrders
FROM Customers c LEFT JOIN
Orders o
ON c.CustomerID = o.CustomerID AND o.FiscalYear = '2016'
GROUP BY c.CustomerID;
TotalTotalOrders
应该是所有订单(或至少是有效客户ID的订单)。
答案 2 :(得分:0)
这将列出所有客户,无论他们是否有任何订单,无论订单的年份如何。然后Sub SpitValues()
Dim dvCell As Range
Dim inputRange As Range
Dim c As Range
Dim i As Long
'Which cell has data validation
Set dvCell = Worksheets("Sheet1").Range("G11")
'Determine where validation comes from
Set inputRange = Evaluate(dvCell.Validation.Formula1)
i = 1
'Begin our loop
Application.ScreenUpdating = False
For Each c In inputRange
dvCell = c.Value
Worksheets("SECURITIZATION").Cells(i, "A1").Value = Worksheets("SECURITIZATION").Range("G30").Value
i = i + 1
Next c
Application.ScreenUpdating = True
将计算2016年下的所有订单,忽略其余订单,并返回一个整数(即它永远不会为空)。
sum