2013-11-27 114 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. 
相關問題