2014-09-23 72 views
1

我一直與SQL幾個月,我無法決定幾件事情對這個特定的任務:我應該使用CTE,子查詢,臨時表還是其他方法?

  1. 可以在SQL輸出的數據,我需要它的方式嗎?
  2. 如果需要,我應該使用哪種方法?

我已經把每個學校按年級劃分了下來,而第二列有每個年級的總入學率。我試圖總結每個年級所有在校學生與下列所需的輸出所有學校:

Grade Total Enrolled 
K  7,871 
1  8,321 
2  8,087 
3  8,164 
4  8,237 
5  8,055 

謝謝您的幫助!

我試過這個使用子查詢,但它顯示了重複在表中的所有記錄每行的總數,而不是隻有一行總計。

子查詢:

SELECT (SELECT SUM(Totalenrollment) FROM Dbo.['2013Cycle_1_Data'] 
    WHERE Grade LIKE '%6%' AND Level = 'MS') AS Grade6 

CTE代碼:

WITH 
    TK AS ( SELECT SUM(Totalenrollment) AS Kindergarten FROM Dbo.['2013Cycle_1_Data'] WHERE Grade LIKE '%KIND%' AND Level = 'ES') 
, T1 AS ( SELECT SUM(Totalenrollment) AS Grade1  FROM Dbo.['2013Cycle_1_Data'] WHERE Grade LIKE '%1%' AND Level = 'ES') 
, T2 AS ( SELECT SUM(Totalenrollment) AS Grade2  FROM Dbo.['2013Cycle_1_Data'] WHERE Grade LIKE '%2%' AND Level = 'ES') 
, T3 AS ( SELECT SUM(Totalenrollment) AS Grade3  FROM Dbo.['2013Cycle_1_Data'] WHERE Grade LIKE '%3%' AND Level = 'ES') 
, T4 AS ( SELECT SUM(Totalenrollment) AS Grade4  FROM Dbo.['2013Cycle_1_Data'] WHERE Grade LIKE '%4%' AND Level = 'ES') 
, T5 AS ( SELECT SUM(Totalenrollment) AS Grade5  FROM Dbo.['2013Cycle_1_Data'] WHERE Grade LIKE '%5%' AND Level = 'ES') 

SELECT * FROM TK 
UNION ALL 
SELECT * FROM T1 
UNION ALL 
SELECT * FROM T2 
UNION ALL 
SELECT * FROM T3 
UNION ALL 
SELECT * FROM T4 
UNION ALL 
SELECT * FROM T5 

回答

3

只需使用CASE語句由年級水平來確定檔次水平,然後組:

select 
    case 
     when Grade LIKE '%KIND%' AND Level = 'ES' then 'K' 
     when Grade LIKE '%1%' AND Level = 'ES' then '1' 
     else 'Other Grades' 
    end as GradeLevel, 
    sum(TotalEnrollment) as Enrolled 
from 
    Dbo.['2013Cycle_1_Data'] 
group by 
    case 
     when Grade LIKE '%KIND%' AND Level = 'ES' then 'K' 
     when Grade LIKE '%1%' AND Level = 'ES' then '1' 
     else 'Other Grades' 
    end 
+0

哇。謝謝@凱爾。這是一個更簡單和合乎邏輯的方法。我感謝您的幫助! – JM1 2014-09-23 17:19:02

相關問題