2017-07-27 77 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