T-SQL,连接上不匹配的零和
我有两张表,一张包含我所有的分支机构,一张包含我所有的销售额。 销售表还包含销售代表 ID、分支机构 ID、月份和年份。
我需要一个查询,该查询将返回特定代表一年的销售额总和(按分支机构和月份分组),并且如果该月分支机构没有销售额,则该查询必须返回 0。 我有以下内容,如果没有销售,则不会返回 0:
SELECT
s.Month,
b.BranchName,
SUM(s.InvoiceAmount) AS 'Sales'
FROM
Branch b
INNER JOIN
Sales s ON s.BranchID = b.BranchID
WHERE
s.Year = 2008
AND
s.SalesRepID= 11
GROUP BY
s.Month,
b.BranchName
ORDER BY
s.Month,
b.BranchName
I have two tables, one with all my Branches, and one with all my sales. The sales table also contains a Sales Rep ID, a Branch ID, a month and a year.
I need a query that will return the sum of a specific rep's sales for a year, grouped by branch and month, and the query must return 0 if there has been no sales in a branch for that month. I have the following, which does not return 0 if there are no sales:
SELECT
s.Month,
b.BranchName,
SUM(s.InvoiceAmount) AS 'Sales'
FROM
Branch b
INNER JOIN
Sales s ON s.BranchID = b.BranchID
WHERE
s.Year = 2008
AND
s.SalesRepID= 11
GROUP BY
s.Month,
b.BranchName
ORDER BY
s.Month,
b.BranchName
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要使用左连接和 isnull 来获得正确的总和:
如果销售员在特定月份没有销售额,您仍然需要对其进行更多操作才能显示月份。
You need to use a left join and an isnull to get the sum right:
You still need to do some more work with it to get the months showing too if a salesman has no sales in a particular month.
我将连接从内部更改为左外部,并为没有销售的分支添加了 ISNULL 函数。
I changed the join from inner to left outer and added the ISNULL function for branches with no sales.
您需要添加“缺失”的数据才能加入。
You will need to add the "missing" data to be able to join it.
您需要对 Sales 执行 LEFT JOIN,以便返回 Sales 表中没有任何记录的代表。
You'll need to do a LEFT JOIN to Sales, so as to return even the reps that do not have any records in the Sales table.
如果您的查询返回 NULL,您可以使用其中一种合并方法:
COALESCE(SUM(...), 0)
将返回列表中的第一个非 NULL 值...If your query is returning NULL, you can use one of the coalescing methods:
COALESCE(SUM(...), 0)
will return the first non-NULL value in the list...