使用子查询在具有不同where子句的列上添加

时间:2019-05-02 18:10:58

标签: sql subquery

我有一个查询,它从当年提取数据,并且我试图使用子查询在上一年的新列中添加数据,因为主查询的WHERE语句将其限制为当年。我不断收到错误消息,子查询返回多个值,但是当我只运行子查询时,每个ID仅一个值。我以前是分别运行这两个查询,并在Excel中使用vlookup来加入最后一列,但是我很想在一个查询中执行此操作。

SELECT DISTINCT student_master.id_num,  stud_term_sum_div_a.trm_gpa,  
       (SELECT stud_term_sum_div_b.trm_gpa  
        FROM student_master LEFT OUTER JOIN
             stud_term_sum_div stud_term_sum_div_b
             ON student_master.id_num = stud_term_sum_div_b.id_num 
        WHERE ( stud_term_sum_div_b.yr_cde = '2018'
       ) A AS Prev_GPA
FROM student_master LEFT OUTER JOIN
     stud_term_sum_div stud_term_sum_div_a
     ON student_master.id_num = stud_term_sum_div_a.id_num
WHERE stud_term_sum_div_a..yr_cde = '2019' 

我希望会有3列-学生证,2019 gpa,2018 gpa

1 个答案:

答案 0 :(得分:0)

要获得您在问题中提到的特定年份,可以使用Case语句执行以下操作:

SELECT DISTINCT student_master.id_num, 
    Case when stud_term_sum_div.yr_cde = '2018' then stud_term_sum_div.trm_gpa end as '2018 GPA',  
    Case when stud_term_sum_div.yr_cde = '2019' then stud_term_sum_div.trm_gpa end as '2019 GPA'
FROM student_master LEFT OUTER JOIN
     stud_term_sum_div 
     ON student_master.id_num = stud_term_sum_div.id_num
WHERE stud_term_sum_div.yr_cde in ('2018','2019')

要获得今年和去年而不使用特定日期的信息:

SELECT DISTINCT student_master.id_num, 
    Case when CAST(stud_term_sum_div.yr_cde as int) = year(getdate())-1 then stud_term_sum_div.trm_gpa end as 'Last GPA',  
    Case when CAST(stud_term_sum_div.yr_cde as int) = year(getdate()) then stud_term_sum_div.trm_gpa end as 'Current GPA'
FROM student_master LEFT OUTER JOIN
     stud_term_sum_div 
     ON student_master.id_num = stud_term_sum_div.id_num
WHERE CAST(stud_term_sum_div.yr_cde as int) >= year(getdate())-1