English 中文(简体)
页: 1 服务器多个表格,具体日期从许多
原标题:SQL Server multiple tables query for a specific date from many
  • 时间: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

下表显示:

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

我的问题是,我如何从表(1)中找到从事两项活动的所有成员的第二次活动(表2),并从表3中检索与这项活动有关的信息。

预 收

最佳回答

罗位职能有助于你出席。

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

我在此将数据按成员分类,并命令进行该项活动,但可能要按日期进行?

问题回答

与“@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




相关问题
Export tables from SQL Server to be imported to Oracle 10g

I m trying to export some tables from SQL Server 2005 and then create those tables and populate them in Oracle. I have about 10 tables, varying from 4 columns up to 25. I m not using any constraints/...

SQL server: Can NT accounts be mapped to SQL server accounts

In our database we have an SQL server account that has the correct roles to access some of the databases. We are now switching to windows authentication and I was wondering if we can create a NT user ...

SQL Server 2000, ADO 2.8, VB6

How to determine if a Transaction is active i.e. before issuing Begin Transaction I want to ensure that no previous transaction are open.. the platform is VB6, MS-SQL Server 2000 and ADO 2.8

热门标签