SQL Update基于列的评估

时间:2014-02-18 20:45:49

标签: sql sql-server

我想知道是否有一种简单的方法可以在T-SQL中使用CASE和IF / ELSE语句来提出一个查询,该查询将比较enrollment_date所在的行之间的列course_id教师之间也一样。以下是上下文:

select u.user_id, cu.enrollment_date, cm.course_id from course_users cu
join course_main cm on cu.crsmain_pk1 = cm.pk1
join users u on cu.users_pk1 = u.pk1
where cu.role = 'P' and cm.course_id like '%SP2014' and (cu.row_status = 0 or cu.row_status = 2)
order by course_id asc

此查询返回课程中所有教师注册及其注册日期的列表。返回行的示例:

user_id         enrollment_date           course_id
dennismennis    2014-01-27 14:55:30.253    MATH-101
stevenspielberg 2014-01-27 14:55:30.413    MATH-102
lemmings        2014-01-27 14:55:30.300    MATH-103
johndoe         2014-01-27 14:55:24.750    ENGL-101
bobsmith        2014-01-28 14:55:24.790    ENGL-101
susysweet       2014-01-29 14:55:24.737    ENGL-101

我需要做的是查看这些行,并将注册日期与仅在一组course_id之间的user_ids相同的行进行比较。例如,我跳过前3个教师注册,因为他们的course_id不一样,所以我不必担心多个注册到同一个班级。我想要查找的比较是最近的enrollment_date所以enrollment date greater than any other enrollment date that came before for the same course_id between these user_ids

另一个问题是我的select语句不会简单地返回3行,因为我已经写了它返回901行所以我需要查看这些结果然后相应地更新。

基本上我正在寻找的查询将提供所需的比较,然后是update course_users set row_status = 2 where enrollment_date greater than any other enrollment date for the same course_id amongst other instructors.

谢谢!

根据以下答案修改查询:

Merge course_users AS T
Using (
    Select max(cu.enrollment_date) as EnrollDate, cm.course_id from course_users cu
join course_main cm on cu.crsmain_pk1 = cm.pk1
join users u on cu.users_pk1 = u.pk1
where cu.role = 'P' and cm.course_id like '%SP2014' group by cm.course_id
) As SRC ON SRC.Course_ID = T.crsmain_pk1 and SRC.EnrollDate != T.enrollment_date
WHEN MATCH 
THEN UPDATE SET T.row_status = 2;

MATCH收到错误的语法?应该是MATCHED吗?

1 个答案:

答案 0 :(得分:1)

您需要调查利用合并功能来执行此任务。此代码旨在让您了解去哪里。您是架构的专家,因此您将能够找出course_users表中的course_id。

Merge course_users AS T
Using (
    Select max(cu.enrollment_date) as EnrollDate, cm.course_id from cte group by course
) As SRC ON SRC.Course_ID = T.Course_ID and SRC.EnrollDate != T.enrollment_date
WHEN MATCHED 
    THEN UPDATE SET T.row_status = 2;

以下是合并功能MSDN article的链接。