SQL,刚刚从多对多关系中获取(在一行中)

时间:2014-10-29 02:24:11

标签: sql sql-server join many-to-many

我有3张表,比如

A. (Aid,person)

B. (Bid,event,InsertDate)

C. (Cid,Aid,Bid)

现在我需要在加入B.InsertDateB.event的{​​{1}} desc上获取最近的最新活动基数(每个人的最后一次活动) 我尝试了加入,但这会产生多个A.PersonA.Person。 你能指导我吗?

更新

现在我只是将另一个lastUpdate列添加到person表中,并为Event表中的每个插入更新,并使其等于InsertDate。所以我的查询就像:

B.event

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT
  A.person,
  B.event,
  MAX(B.InsertDate)
FROM
  A
  JOIN C ON A.Aid = C.Aid
  JOIN B ON B.Bid = C.Bid
GROUP BY
  A.person,
  B.event

答案 1 :(得分:1)

可能是这样的

WITH cte
     AS (SELECT Row_number() OVER (partition BY person ORDER BY B.InsertDate DESC) rn,
                A.person,
                B.event,
                B.InsertDate                    AS LastEventDate
         FROM   B
                JOIN (SELECT B.event,
                             Max(B.InsertDate) InsertDate
                      FROM   B
                      GROUP  BY B.event) sub
                  ON sub.event = B.event
                     AND sub.InsertDate = b.InsertDate
                JOIN A
                  ON A.Bid = C.Bid
                JOIN C
                  ON B.Bid = C.Bid)
SELECT *
FROM   cte
WHERE  rn = 1