how to combine three sql selects into one query

前端 未结 2 1678
你的背包
你的背包 2021-01-29 10:09

I have the three queries below, I would like to combine them into one query so I get three columns with results by county. I tried doing an inner join with all of the tables, b

相关标签:
2条回答
  • 2021-01-29 10:38

    One way to do it would be to convert your existing queries into inline tables like this - you don't need the select from Counties table as you've already got that table in your first two queries:

    select co.Description, a.[Total DLL Children], b.[Total Children]
    from
    (select co.id,[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.id, co.Description) a
     join 
     (select co.id, co.Description, [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.id, co.Description) b on a.id = b.id
    
    0 讨论(0)
  • 2021-01-29 10:43

    Please try this. Basically, each subquery, you need to return County.Description too, then you can join them together.

    
     SELECT A.Description, B.[Total DLL Children], C.[Total Children]
     FROM (
         select co.Description from Counties as co
         group by co.Description
         ) A
     LEFT JOIN 
         (
             select co.Description, [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
          ) B
          ON A.DESCRIPTION = B.DESCRIPTION 
    LEFT JOIN 
          (
             select co.Description, [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
          ) C
          ON A.DESCRIPTION = C.DESCRIPTION 
    
    0 讨论(0)
提交回复
热议问题