SQL Server多个表从多个查询特定日期

时间:2012-05-17 19:03:56

标签: sql-server

我有三张桌子:

表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个活动的所有成员的第二个活动的ID和日期(表2),并从表3中检索与此活动ID相关的信息。

提前致谢

2 个答案:

答案 0 :(得分: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对活动进行了排序,但也许您想按日期订购?

答案 1 :(得分: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