2013-03-27 101 views
0

我有三个查询下面,我想将它们合并成一个查询,所以我得到三个县的结果列。我尝试了与所有表的内部连接,但是我收到了错误的数据。我如何结合这三个查询和县组?SQL查询合并

select co.Description 
from Counties as co 
group by co.Description 


select [Total DLL Children] = SUM(cd.NumberOfLanguageSpeakers) 
from ClassroomDLL as cd 
    inner join Classrooms as c on cd.Classroom_Id = c.Id 
    inner join Sites as s on c.Site_Id = s.Id 
    inner join Profiles as p on s.Profile_Id = p.Id 
    inner join Counties as co on p.County_Id = co.Id 
group by co.Description 


select 
    [Total Children] = (SUM(demo.NumberOfPreschoolers) 
    + SUM(demo.NumberOfToddlers) + SUM(demo.NumberOfInfants)) 
from ClassroomDemographics as demo 
    inner join Classrooms as c on demo.Classroom_Id = c.Id 
    inner join Sites as s on c.Site_Id = s.Id 
    inner join Profiles as p on s.Profile_Id = p.Id 
    inner join Counties as co on p.County_Id = co.Id 
group By co.Description 
+0

我们在谈论什么口味的SQL办呢? – 2013-03-27 17:21:49

+1

与以前的问题有什么不同? http://stackoverflow.com/questions/15663727/how-to-combine-three-sql-selects-into-one-query – Taryn 2013-03-27 17:24:31

回答

1

你可以使用子查询

select co.Description, demo.[Total Children], cd.[Total DLL Children] 
from Classrooms as c 
left outer join (select SUM(NumberOfPreschoolers) + SUM(NumberOfToddlers) + SUM(NumberOfInfants) as [Total Children], Classroom_id 
        from ClassroomDemographics group by Classroom_id) as demo on demo.Classroom_id = c.Id 
left outer join (select SUM(NumberOfLanguageSpeakers) as [Total DLL Children], Classroom_id 
        from ClassroomDLL group by Classroom_id) as cd on cd.Classroom_id = c.Id 
inner join Sites as s on c.Site_Id = s.Id 
inner join Profiles as p on s.Profile_Id = p.Id 
inner join Counties as co on p.County_Id = co.Id 
group By co.Description