SQL查询连接2个表并根据条件查找匹配的行

时间:2012-10-26 04:23:55

标签: sql

假设我正在尝试构建一个SQL查询来查找自2012年6月1日以来没有进行过销售的所有人,并且我有2个表:

UserID    FirstName    LastName
1000      Ted          Ting
1001      Sally        Song
1002      Adam         Apple

UserID   SalesDate
1000     8/1/2012
1000     6/12/2012
1000     6/11/2012
1000     5/3/2012
1001     3/1/2012
1001     5/30/2012
1002     6/15/2012
1002     5/1/2011

此查询的结果将包含列:

UserID   FirstName   LastName  LastSalesDate
1001     Sally       Song      5/30/2012

请注意,这只是返回Sally的最新销售,而不是所有销售日期之前(它没有显示2012年3月1日的销售)。什么是正确的SQL查询来获得这个?

3 个答案:

答案 0 :(得分:1)

SELECT t1.UserID, t1.FirstName, t1.LastName, MAX(SalesDate) AS SalesDate
FROM Table1 t1 JOIN Table2 t1 ON t1.UserId = t2.UserID
GROUP BY t1.UserID, t1.FirstName, t1.LastName
HAVING MAX(SalesDate) < '20120601'

答案 1 :(得分:0)

基本上你只需要根据用户ID在表上进行内连接。然后你可以使用在哪里过滤你定义的日期。

select top 1 * from table1 as t1 
  inner join table2 as t2 on t2.userid = t1.userid 
  where t2.lastsalesdate < '6/1/2012' order by t2.lastsalesdate desc;

答案 2 :(得分:0)

select t.userid,t.firstname,t.lastname,max(t1.salesdate) as lastsalesdate 
from table1 as t1 
left outer join table2 as t2 on t2.userid = t1.userid 
where t1.userid not in(select t3.userid from table2 where t3.lastsalesdate < '6/1/2012')
group by t2.userid;