0

假设我正在尝试构建一个 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 查询是什么?

4

3 回答 3

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'
于 2012-10-28T03:06:24.107 回答
0

基本上,您只需要根据用户 ID 对表进行内部联接。然后您可以使用 where 过滤您定义的日期。

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;
于 2012-10-26T04:28:04.450 回答
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;
于 2012-10-26T04:31:43.493 回答