当标准可以在任何一个表上时,如何在1对多关系上执行搜索?

时间:2010-11-12 16:15:59

标签: tsql

我正在使用t-sql。我有我认为简单的搜索。 SalesPerson和TradeShow之间存在1对多的关系。 1位销售人员可以参加很多贸易展览会。我需要能够搜索SalePerson。我还需要能够在他们参加的最后一个贸易展上进行搜索。我以为我可以在他们的最后一个贸易展上做简单的加入和分组,但我无法展示城市或州。

SELECT     SalePersonID, FirstName, LastName, TradeShow.DateLastWent
FROM         SalesPerson INNER JOIN
(SELECT     SalePersonID, MAX(DateLastWent) AS DateLastWent
     FROM TradeShow 
 GROUP BY SalesPersonID) AS TradeShow ON SalesPerson.SalePersonID= TradeShow.SalePersonID

这可以,但贸易展也有城市和州。我需要能够搜索并显示城市和州。但是如果我将它们包含在子查询中,我必须将它包含在聚合函数中,如果我这样做,我会得到错误的城市和州。

表格很简单

SALEPERSON salespersonID PK 名字 名字

TRADESHOW tradeshowID PK datelastwent 市 州 salespersonID FK

3 个答案:

答案 0 :(得分:1)

重新说一下:你想要的是销售人员,以及他们去过的最后一个节目的信息。

Select
  SalePersonID, 
  FirstName, 
  LastName, 
  TradeShow.DateLastWent,
  TradeShow.City,
  TradeShow.State
From
  SalesPerson
  Inner Join TradeShow 
    On SalesPerson.SalePersonID = TradeShow.SalePersonID
Where
  TradeShow.TradeShowID =
    (Select Top 1 Latest.TradeShowID
     From TradeShow As Latest
     Where SalesPerson.SalePersonID = Latest.SalePersonID
     Order By Latest.DateLastWent Desc)

答案 1 :(得分:0)

可能有更优雅的方式来解决这个问题,但我的第一个想法是简单地抓住最新的TradeShow记录加入

SELECT SalePersonID, FirstName, LastName, TradeShow.DateLastWent 
  FROM SalesPerson 
       INNER JOIN (
                   SELECT *
                     FROM (
                           SELECT TradeShowId, DateLastWent, City, State, SalesPersonId
                             FROM TradeShow  
                         ORDER BY datelastwent DESC
                          )
                    WHERE ROWNUM <= 1
                  ) ON SalesPerson.SalesPersonId = TradeShow.SalesPersonId 

修改

哎呀......过多地玩Oracle了

ROW_NUMBER() OVER(order by date) or SELECT TOP X

这将是SQL Server这样做的方式...没有运行SQL-Server的实例,但很确定语法最终会像

SELECT SalePersonID, FirstName, LastName, TradeShow.DateLastWent  
  FROM SalesPerson  
       INNER JOIN ( 
                   SELECT TradeShowId, DateLastWent, City, State, SalesPersonId, ROW_NUMBER() OVER(PARTITION BY TradeShow.SalesPersonId ORDER BY DateLastWent DESC) RowNumber
                     FROM TradeShow   
                  ) ON SalesPerson.SalesPersonId = TradeShow.SalesPersonId AN TradeShow.RowNumber = 1

答案 2 :(得分:0)

您可以两次加入TradeShow:

SELECT     SalePersonID, FirstName, LastName, TS1.DateLastWent,
  TS2.City, TS2.State 
FROM         SalesPerson INNER JOIN
 (SELECT     SalePersonID, MAX(DateLastWent) AS DateLastWent
 FROM TradeShow 
 GROUP BY SalesPersonID
 ) AS TS1 ON (SalesPerson.SalePersonID= TradeShow.SalePersonID)
INNER JOIN TradeShow TS2 ON 
 (TS2.SalePersonID = TS1.SalePersonID AND TS2.DateLastWent = TS1.DateLastWent)
WHERE TS2.City = 'CityName'