2017-07-27 75 views
1

我有一个课程表:c_inst,c_year,c_program_type,c_unique_key。我想知道从2016年到2017年,c_program_type从'V'变为'P',反之亦然。我遇到问题需要运行。以下是我已经尝试过,我知道这只是平了错误:尝试选择上一年发生更改的所有记录

select * from courses a 
where c_program_type in ('P','V') 
and c_year = '2017' 
and c_program_type != (select c_program_type from courses b where 
         a.c_unique_key = b.c_unique_key and c_year = '2016') 

什么是一个SQL小白做到这一点,最简单的方法?我也试过使用SQL服务器临时表,但没有运气。提前致谢!

+1

当您切换“V”和“P”之间的行,你更新现有行或添加一个新的?如果是后者,你怎么标记旧行已经过时? – Cowthulhu

+0

P和V是'c_program_type'的唯一允许值还是有更多的可能性? – Haris

+0

c_program_type有更多的可能性,但我特别关注P和V. – Emily

回答

1

您可以尝试

SELECT a.* 
FROM courses a 
     LEFT JOIN courses b 
       ON a.c_unique_key = b.c_unique_key 
       AND a.c_program_type = b.c_program_type 
       AND b.c_year = '2016' 
WHERE a.c_program_type IN ('P', 'V') 
     AND a.c_year = '2017' 
     AND b.c_unique_key IS NULL