2013-11-27 140 views
0

我是初学者到sql数据库 我想要一些帮助....我有两个表(families_table)和(children_table)通过family_id关联,所以家庭表中的每个家庭都有很多儿童表儿童... 我要选择从家庭餐桌一些家庭,知道孩子的数量为所有选定的家庭。我试图通过sql select table from another table values

select count (*) from dbo.Children where family_id in (select top 50 percent * from dbo.Families where economic_state = 'a' or economic_state = 'j') 

回答

1

要做到这一点,您可以使用group bycount对于这样的查询:

select f.family_id, count(*) 
from dbo.Families f 
inner join dbo.Children c ON c.family_id = f.family_id 
where f.economic_state = 'a' or f.economic_state = 'j' 
group by f.family_id 

编辑:

如果您只需要返回前50%,您可以简单地将其添加到上面的查询。由于它的加入,先算,它会从连接结果返回50%:

select top 50 percent f.family_id, count(*) 
from dbo.Families f 
inner join dbo.Children c ON c.family_id = f.family_id 
where f.economic_state = 'a' or f.economic_state = 'j' 
group by f.family_id 
+0

我不想只从家庭表中选择family_id ..我想从家庭表中选择50%。 – Hamonbatra

+1

您可以将该查询包装在另一个Select查询中以获取其余信息。 – davidgarrison

+0

我尝试你的代码,并将儿童计数分配给文本框..但每次返回值文本框是1 ...为什么? – Hamonbatra

1

从Szymon的回答修改,允许你以包括表中的其他列。

select * 
FROM 
    (select f.family_id, count(*) children 
    from dbo.Families f 
    inner join dbo.Children c ON c.family_id = f.family_id 
    where f.economic_state = 'a' or f.economic_state = 'j' 
    group by f.family_id) fc 
JOIN dbo.Families f ON f.family_id = fc.family_Id 
0

使用加入和group by:

SELECT children.fid, families.eco_state, count(children.fid) FROM children, families where children.fid= families.id and families.eco_state = 'a' 

集团通过children.fid

0

您可以使用公用表表达式(CTE)来编写可读性这样的查询。

;With CteFamily AS 
(
SELECT family_id FROM dbo.Families 
--WHERE --Put your conditions to filter family 
), 
--get childrens count, with family id for selected family 
CteChildrenCount AS 
(
SELECT family_id , Count(*) As ChildrenCount 
FROM dbo.Children 
WHERE family_id IN (SELECT family_id FROM CteFamily) 
GROUP BY family_id 
), 
--final query to get all other details from family table 
CteFamilyDetails AS 
(
    SELECT f.economic_state,f.family_id ,ChildrenCount --Add extra columns from family  --table here 
    FROM dbo.Families f 
INNER JOIN CteChildrenCount c 
ON f.family_id = c.family_id 
) 
SELECT * FROM CteFamilyDetails; --End of Cte end with semicolon. 
相关问题