我应该使用CTE,子查询,临时表还是其他方法?

时间:2014-09-23 17:10:39

标签: sql sql-server tsql

我已经使用SQL几个月了,我在为这项特定任务确定一些事情时遇到了麻烦:

  1. SQL能否以我需要的方式输出数据?
  2. 如果是这样,我应该使用哪种方法来实现?
  3. 我所拥有的表格按照年级分列了每所学校,第二栏有每个年级的总入学率。我正在努力为所有学校的所有入学学生提供以下所需产出的总和:

    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 
    

1 个答案:

答案 0 :(得分: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