Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 尝试选择上一年发生更改的所有记录_Sql_Sql Server - Fatal编程技术网

Sql 尝试选择上一年发生更改的所有记录

Sql 尝试选择上一年发生更改的所有记录,sql,sql-server,Sql,Sql Server,我有一张课程表:课程设置,课程年,课程类型,课程唯一键。我想知道从2016年到2017年,c_课程类型从“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

我有一张课程表:课程设置,课程年,课程类型,课程唯一键。我想知道从2016年到2017年,c_课程类型从“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') 
对于SQLNoob,最简单的方法是什么?我也尝试过使用sql server临时表,但在这方面运气不好。提前谢谢

你可以试试

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 

在“V”和“P”之间切换行时,是更新现有行还是添加新行?如果是后者,您如何标记旧行现在已过时?P和V是
c_program_type
唯一允许的值还是有更多的可能性?c_program_type有更多的可能性,但我特别关注P和V。我们不更新现有行,但是,当我们从机构那里得到它们时,我们确实增加了一个新的记录,这就是为什么我们试图检查这些程序类型何时发生了变化,如果这有意义的话。我知道有一种更好的方法来标记旧行现在已过时,但这是目前唯一可以验证数据的方法