1

我有三张桌子:

表 1 - 成员

Id   Name
1    Member1
2    Member2

表 2 - 活动

Id   Member_id   Activity    Date
 1      1        Activity1   2001-1-1
 2      1        Activity2   2001-2-1
 3      1        Activity3   2001-3-1
 4      2        Test        2010-4-1

表 3 – 详细

Id  Activity_id Information
1   2       Information

从以下可以看出,成员 id 1 具有三个活动:

SELECT Member.id, COUNT(*) AS number
FROM Member 
INNER JOIN Activity ON Activity.Member_ID = Member.id
GROUP BY Member.id

我的问题是如何从表(1)中找到所有有 2 个活动的成员的第二个活动(表 2)的 ID 和日期,并从表 3 中检索与此活动 ID 相关的信息。

提前致谢

4

2 回答 2

1

行号功能将在这里为您提供帮助。

select *
from (
    select 
        *,
        rn = row_number() over (partition by member_id order by id)
    from
        activity
) activityWithRn
inner join detailed on detailed.activity_id = activityWithRn.id
where activityWithRn.rn = 2

在这里,我按成员 ID 对数据进行了分区,并按其 ID 对活动进行了排序,但也许您想按日期排序?

于 2012-05-17T19:36:03.183 回答
0

同意@mouters,这个ROW_NUMBER()功能在这里确实很有帮助。但我认为排名的使用方式应该与@mouters 所建议的略有不同。

这是我的解决方案尝试:

WITH ranked AS (
  SELECT
    *,
    rn = ROW_NUMBER() OVER (PARTITION BY Member_id)
  FROM Activity
)
SELECT
  a.Member_id,
  number      = COUNT(*),
  Activity_id = MAX(d.Activity_id),
  Information = MAX(d.Information)
  Date        = MAX(CASE WHEN d.Id IS NOT NULL THEN a.Date)
FROM ranked a
  LEFT JOIN Detailed d ON a.Id = d.Activity_id AND a.rn = 2
GROUP BY a.Member_id
于 2012-05-17T20:42:45.490 回答