【发布时间】:2021-09-16 09:21:36
【问题描述】:
我正在尝试根据学生所学的课程分配一个代码。当学生参加两门课程时,问题就来了。在这种情况下,应该为它们分配一个代码,并且应该只为它们返回一条记录,而不是两条。我在下面解释结果应该是什么样子。
--Create table:
CREATE TABLE [dbo].[Courses](
[TermCode] [varchar](5) NULL,
[StudentID] [varchar](9) NULL,
[CourseCode] [varchar](6) NULL
) ON [PRIMARY]
GO
--Insert Records:
Insert into Courses (TermCode, StudentID, CourseCode)
values ('20211', '123456789', '100001');
Insert into Courses (TermCode, StudentID, CourseCode)
values ('20211', '234567890', '400001');
Insert into Courses (TermCode, StudentID, CourseCode)
values ('20211', '345678901', 'BH0001');
Insert into Courses (TermCode, StudentID, CourseCode)
values ('20211', '456789012', 'BH0002');
Insert into Courses (TermCode, StudentID, CourseCode)
values ('20211', '567890123', '100001');
Insert into Courses (TermCode, StudentID, CourseCode)
values ('20211', '567890123', 'BH0001');
Insert into Courses (TermCode, StudentID, CourseCode)
values ('20211', '678901234', '400001');
Insert into Courses (TermCode, StudentID, CourseCode)
values ('20211', '678901234', 'BH0002');
-- 到目前为止我所拥有的:
select StudentID,
case
when CourseCode = '100001' then 'AAN1'
when CourseCode = '400001' then 'AAN4'
when CourseCode = 'BH0001' then 'BABH'
when CourseCode = 'BH0002' then 'BPBH'
when (CourseCode = '100001' and CourseCode = 'BH0001') then 'BH01'
when (CourseCode = '400001' and CourseCode = 'BH0002') then 'BH04'
end as CustomCode
from Courses
-- 我得到的结果:
| StudentID | CustomCode |
| --------- | ---------- |
| 123456789 | AAN1 |
| 234567890 | AAN4 |
| 345678901 | BABH |
| 456789012 | BPBH |
| 567890123 | AAN1 |
| 567890123 | BABH |
| 678901234 | AAN4 |
| 678901234 | BPBH |
我需要的结果:
| StudentID | CustomCode |
| --------- | ---------- |
| 123456789 | AAN1 |
| 234567890 | AAN4 |
| 345678901 | BABH |
| 456789012 | BPBH |
| 567890123 | BH01 |
| 678901234 | BH04 |
这样做的问题是它可以很好地评估单个课程。它正在检查两门课程的线路不起作用。 StudentID 567890123 和 678901234 应该返回一条记录,而不是两条。我不确定我做错了什么。
【问题讨论】:
-
您的
case语句在单行中运行。所以不可能有CourseCode同时等于两个不同的值。 -
case表达式. -
戈登林诺夫,你的建议奏效了!非常感谢!