从两个表SQLSERVER 2008中获取前三名

时间:2014-01-29 19:05:49

标签: sql join

我在数据库中有两个表:

dbo.Family 
dbo.Family_member 

relationship between them one-to-many

每个家庭都有一个或多个家庭成员 内连接条件是:

on dbo.Family.F_id = dbo.Family_member.FM_f_id

我需要一个查询来获取其中成员数量最多的前3个家庭的ID

这意味着我应该计算每个家庭的family_member中有多少记录然后按decs排序然后排在前3位

你可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您需要在家庭ID字段上执行“分组依据”;查询将如下所示:

SELECT TOP 3 dbo.Family.F_id
FROM dbo.Family 
INNER JOIN dbo.Family_member
ON dbo.Family.F_id = dbo.Family_member.FM_f_id
GROUP BY dbo.Family.F_id
ORDER BY count(*) DESC 

答案 1 :(得分:0)

试试这个:

select TOP 3 *, (select count(dbo.Family_member.FM_f_id) 
from dbo.Family_member where dbo.Family_member.FM_f_id = dbo.Family.F_id) 
winners from dbo.Family order by winners desc