右表有空值时,2个表的T-SQL Correct Join方法

时间:2014-10-01 16:02:30

标签: sql sql-server

感觉就像一个dufus并且缺少一些简单的东西。左表是Employee,其中一列名为EmployeeCode。右表为Invoices,其中一列名为SalesPerson,另一列为TotalAmount列,其中包含销售值。

在任何一周内,并非所有员工都会有发票。如果给定员工没有发票记录,我需要查询返回所有员工并在销售列中返回0。目前,我的查询仅显示包含匹配员工的发票的行。

这是我有缺陷的查询尝试 - 它只返回给我开具发票金额的员工。

SELECT 
   E.LastName,
   E.FirstName,
   E.DefaultDept,
   E.EmployeeCode,
   ISNULL(SUM(I.TotalAmount), 0) As Sales
FROM
   Employee As E 
LEFT OUTER JOIN
   Invoice As I On E.EmployeeCode = I.Salesperson
WHERE
   IsTechnician = 1
   AND IsActive = 1
   AND PostDate >= '2014-08-25' AND PostDate <= '2014-08-31'
GROUP BY
   EmployeeCode, 
   LastName, FirstName,
   DefaultDept
ORDER BY
   LastName

1 个答案:

答案 0 :(得分:0)

如果WHERE子句中的任何列:

Where IsTechnician = 1
AND IsActive = 1
AND PostDate >= '2014-08-25' AND PostDate <= '2014-08-31'

来自invoice表,可能会导致您看到的行为。如果这些列中的任何一列来自invoice表,您需要检查NULL或所需的值。例如:

AND (PostDate IS NULL OR (PostDate >= '2014-08-25' AND PostDate <= '2014-08-31'))