左连接中右侧表中的更多记录

时间:2014-04-29 15:26:54

标签: sql sql-server sql-server-2008

  Table_A                    Table_Audit
  Id    Name               Id    Table_A_Id     Event           Date   
   1     A                 1          1          Cancelled     20-01-2014
   2     B                 2          1          Renewed       21-01-2014
                           3          1          Cancelled     22-01-2014

表有一个Audit表。如您所见,Table_A_Id有多个Cancel事件。我希望将Table_A与Audit结合使用以获得最高的取消日期。

  SELECT TA.*,A.Date FROM Table_A TA
  LEFT JOIN Audit A
  On TA.Id = A.Table_A_Id AND A.Event ='Cancelled'

有人可以建议我如何修改以获得最高的取消日期

5 个答案:

答案 0 :(得分:1)

如果您只想从审计表中提取最大日期,请先进行聚合,然后再进行连接:

SELECT TA.*, A.MAXDate
FROM Table_A TA LEFT JOIN
     (SELECT A.Table_A_Id, MAX(A.DATE) as MAXDATE
      FROM Audit A
      WHERE A.Event = 'Cancelled'
      GROUP BY A.Table_A_Id 
     ) A
     On TA.Id = A.Table_A_Id;

答案 1 :(得分:0)

我假设Table_A中始终存在与Table_Audit相关联的条目,但并不总是反过来? 在这种情况下,左连接最有可能优先于右连接。

在MS-SQL中使用临时表的示例:

declare @TABLE_A table(
ID int
, Name varchar(8)
)

INSERT INTO @TABLE_A (ID, Name)
select 1, 'A'
union all
select 2, 'B'

declare @Table_Audit table(
ID int
, Table_A_Id int
, "Event" varchar(16)
, "Date" date
)

insert into @Table_Audit (ID, Table_A_Id, "Event", "Date")
select 1, 1, 'Cancelled', '2014-01-20'
union all
select 2, 1, 'Renewed', '2014-01-21'
union all
select 3, 1, 'Cancelled', '2014-01-22'


select
  a.ID
, a.Name
, ta.Date
from @TABLE_A a
left join @Table_Audit ta on ta.Table_A_Id = a.ID
where 1=1
and ta.Event = 'Cancelled'
and ta.Date = (select max(tai.Date)
               from @Table_Audit tai
               where tai.Event = 'Cancelled'
               and tai.Table_A_Id = ta.Table_A_Id
)

答案 2 :(得分:0)

我认为GROUP BY和MAX应该做到这一点。

SELECT TA.*, A.MaxDate
FROM Table_A TA
     LEFT JOIN (SELECT Table_A_ID, Event, MAX(Date) MaxDate
                FROM Table_Audit 
                WHERE Event = 'Cancelled' 
                GROUP BY Table_A_ID, Event) A
        ON TA.Id = A.Table_A_Id 

答案 3 :(得分:0)

试试这个。这将为您获取每个事件类型和表的最大ID,并显示它们的所有审核。

SELECT ta.*, t.Name
FROM Table_Audit ta
INNER JOIN ( SELECT Table_A_Id, Event, Max(ID) as maxId
             FROM Table_Audit
             GROUP BY Table_A_Id, Event
            ) maxAudits
      ON maxAudits.maxId = ta.ID
INNER JOIN Table_A t on t.Id = ta.Table_A_Id

答案 4 :(得分:0)

SELECT TOP 1 TA.*,A.Date FROM Table_A TA
INNER JOIN Audit A On TA.Id = A.Table_A_Id AND A.Event ='Cancelled'  ORDER BY DATE DESC