2012-10-26 50 views
0

假設我試圖構建一個SQL查詢來查找所有自2012年6月1日以來尚未發售的人,並且我有2個表:SQL查詢加入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查詢來得到這個?

+0

什麼數據庫平臺?有一些方法可以在ANSI SQL中執行此操作,並且有辦法在特定於供應商的SQL中執行此操作。供應商特定的語法通常更清晰。 –

+0

@StuartAinsworth:MS SQL – TMC

回答

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' 
+0

完美,這是它! – TMC

0

基本上,你只需要在基於用戶標識的表上進行內部連接。那麼你可以使用在你定義的日期過濾的地方。

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; 
+0

這不起作用。它在2012年6月1日之前返回所有銷售,而不僅僅是最近的銷售。 – TMC

+0

@TMC根據您的意見更新。不確定你想要-1誰試圖幫助你。 –

+0

Kyle:這隻會返回一行,而不是所有符合條件的行。 – TMC

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; 
+0

這個語法在一些地方似乎是錯誤的。例如'...從表格2 ...中選擇t3.userid。 't3'沒有在任何地方聲明。此外,即使您更正了此錯誤,也會引發t.firstname不在聚合函數或group by子句中的錯誤。 – TMC