2015-11-17 49 views
0

我有這個SQL語句試圖聯合兩個查詢的結果。我怎樣才能得到我使用這條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,這些投入是3和完成1.前4個部分只有投入。

結果集。

enter image description here 我真的很喜歡的是這樣的輸出。

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

。 。 。

謝謝你對此的想法。

回答

0

你想要的不是SQL可以提供給你的東西(至少據我瞭解你的問題)。所有SQL結果都是遊標,而不是每行都具有公共結構。

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 

在單個結果集中導致像這樣的輸出。