1

我有一个表[Users],简化了这个例子:

uID | uName | uSalesRep
----+-------+----------
  1 | John  | 1
  2 | Bob   | 1
  3 | Fred  | 1
  4 | Stu   | 1

还有一张销售表[Activity]

aID | aDate      | aUserID | aText
----+------------+---------+---------------
  1 | 2013-10-09 |       1 | John did stuff
  2 | 2013-10-14 |       2 | Bob did stuff
  3 | 2013-10-17 |       3 | Fred did stuff

我想获取所有销售代表的列表,以及他们从 2013 年 10 月 14 日开始的那一周的活动,这就是我尝试这样做的方式:

SELECT uID, Name, aID, aDate, aText
FROM [Users]
LEFT JOIN [Activity] ON uID = UserID
WHERE (aDate >= '2013-10-14' OR aDate = NULL)
AND (aDate <= '2013-10-18' OR aDate = NULL)
AND uSalesRep = 1

我使用 aLEFT JOIN希望检索所有代表,但我认为这已被aDate要求覆盖。包括aDate = NULL包括根本没有活动的代表,但活动超出指定范围的代表将被忽略。

无论他们记录的任何活动如何,我怎样才能让所有代表至少一次?

谢谢你的时间。

4

1 回答 1

2

当过滤器应用于连接表时,您需要将过滤器放在join,而不是where子句中

SELECT uID, Name, aID, aDate, aText
FROM [Users]
LEFT JOIN [Activity] ON uID = UserID
AND (aDate >= '2013-10-14')
AND (aDate <= '2013-10-18')
WHERE uSalesRep = 1
于 2013-10-21T07:57:41.233 回答