如何使用此SQL语句获取我要查找的输出

时间:2015-11-17 19:16:06

标签: mysql select union

我有这个SQL语句试图将两个查询的结果联合起来。

SELECT s.SectionIndex, COUNT(*) AS [# Drops], s.Name AS section_name, c.DisplayName AS course_name
FROM Enrollments e
JOIN Sections s on s.SectionIndex = e.SectionIndex
JOIN Courses c on c.CourseIndex = s.CourseIndex

WHERE (CAST(StartDate AS DATE) BETWEEN '2014-06-30' AND '2015-06-30') AND   (e.Status like 'DROPPED%')
GROUP BY s.SectionIndex, s.Name, c.DisplayName

UNION ALL

SELECT s.SectionIndex, COUNT(*) AS [# Completes], s.Name AS section_name, c.DisplayName AS course_name
FROM Enrollments e
JOIN Sections s on s.SectionIndex = e.SectionIndex
JOIN Courses c on c.CourseIndex = s.CourseIndex

WHERE (CAST(StartDate AS DATE) BETWEEN '2014-06-30' AND '2015-06-30') AND (e.Status like 'complete%')

GROUP BY s.SectionIndex, s.Name, c.DisplayName
ORDER BY s.SectionIndex

结果集看起来像这样,我认为这是准确的。例如,对于SectionIndex 996,Drop是3和完成1.前4个部分只有下降。

结果集。

enter image description here 我真正喜欢的是这样的输出。

SectionIndex xxx
  # drops xx
  # completions xx
SectionIndex xxx
  # drops xx
  # completions xx

。 。

感谢您对此的看法。

2 个答案:

答案 0 :(得分:0)

你想要的不是SQL能为你提供的东西(至少就我理解你的问题而言)。所有SQL结果都是游标,而不是每行都有通用结构。

答案 1 :(得分:0)

我的同事帮助我以不同的方式看待这个问题。这个SQL将两个查询合并为一个集合,而不像UNION那样将它们拼凑在一起。

select *
 from
 (
  select coalesce(q1.SectionIndex,q2.SectionIndex) as sectionIndex, coalesce(q1.section_name, q2.section_name) as sectionName
 , q1.completions, q2.drops

   from

    (
     select e.SectionIndex, s.Name as section_name, COUNT(e.SectionIndex) as completions
     from Enrollments e
     join Sections s on s.SectionIndex = e.SectionIndex
     join Courses c on c.CourseIndex = s.CourseIndex
     where e.Status like 'COMPLETED'
     AND (CAST(StartDate AS DATE) BETWEEN '2014-06-30' AND '2015-06-30')
     group by e.SectionIndex, s.Name
    ) as q1

/*UNION*/

 full outer join 

   (
    select e.SectionIndex, s.Name as section_name, COUNT(e.SectionIndex) as drops
    from Enrollments e
    join Sections s on s.SectionIndex = e.SectionIndex
    where e.Status like 'dropped'
    AND (CAST(StartDate AS DATE) BETWEEN '2014-06-30' AND '2015-06-30')
    group by e.SectionIndex, s.Name
   ) as q2

 on q1.SectionIndex = q2.SectionIndex

) as q3

order by q3.sectionName

在单个结果集中导致这样的输出。

enter image description here