根据另一行中的值更新行

时间:2015-08-21 10:57:14

标签: sql oracle

所以我试图根据同一个表中另一行的值更新表中的值。以下表为例:

Student #      Subject       Chosen       Required
001            Maths         N            N
054            Maths         N            N
002            History       N            N
001            Geography     Y            N
001            Physics       N            N
054            History       Y            N
002            Physics       Y            N

我想要一个允许我更改“必需”的声明。学生根据他们是否选择了其他科目的专栏:如果001学生选择了数学,他将不需要做物理学。

所以它看起来像:

Update dbo.Subject_Choices
Set Required = 'Y'
Where Subject = 'Physics'
AND
{I have literally no idea how to continue this syntax, but it would have to check whether the required Field for Maths for the same student = N}

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

我认为这应该适合你(修改我的查询以确保它符合Oracle标准):

UPDATE dbo.Subject_Choices SC
SET Required = 'Y'
WHERE Subject = 'Physics'
    AND EXISTS (SELECT 1 FROM dbo.Subject_Choices WHERE Subject = 'Maths' and "student #" = SC."student #" AND Required = 'N');

示例SQLFiddle以及查询的工作方式。