SQL Server 2005 - 如何比较字段值,并在每次出现不同时返回计数
DECLARE @CURRENTSCHOOL TABLE (STUDENT VARCHAR(8), COURSE VARCHAR(8), SCHOOL VARCHAR(2))
INSERT INTO @CURRENTSCHOOL VALUES ('10000000','MCR1010','11')
INSERT INTO @CURRENTSCHOOL VALUES ('12000000','MCR6080','11')
INSERT INTO @CURRENTSCHOOL VALUES ('13000000','MCR6090','15')
DECLARE @OTHERSCHOOLS TABLE (STUDENT VARCHAR(8), COURSE VARCHAR(8), SCHOOL VARCHAR(2))
INSERT INTO @OTHERSCHOOLS VALUES ('10000000','MCR1010','11')
INSERT INTO @OTHERSCHOOLS VALUES ('10000000','MCR1011','14')
INSERT INTO @OTHERSCHOOLS VALUES ('10000000','MCR1012','15')
INSERT INTO @OTHERSCHOOLS VALUES ('12000000','MCR6080','19')
INSERT INTO @OTHERSCHOOLS VALUES ('13000000','MCR6090','15')
对于上面的样本数据。两张桌子。当前学校和其他学校。
Currentschool 是学生当前正在学习的课程,包括学校代码, 并且是主表。
其他学校可能是学生可以在不同学校继续学习的其他课程。
我需要将当前学校表与使用学生 ID 号匹配的其他学校表进行比较,并且对于其他学校中的每个不同学校代码,它需要返回一个计数。
例如:
Student: OtherSchoolCount:
10000000 2 (because of 2 different school codes than than the current school)
12000000 1 (because of 1 different school code than than the current school)
13000000 blank (because not a different school code)
这可能吗?
非常感谢
M。
DECLARE @CURRENTSCHOOL TABLE (STUDENT VARCHAR(8), COURSE VARCHAR(8), SCHOOL VARCHAR(2))
INSERT INTO @CURRENTSCHOOL VALUES ('10000000','MCR1010','11')
INSERT INTO @CURRENTSCHOOL VALUES ('12000000','MCR6080','11')
INSERT INTO @CURRENTSCHOOL VALUES ('13000000','MCR6090','15')
DECLARE @OTHERSCHOOLS TABLE (STUDENT VARCHAR(8), COURSE VARCHAR(8), SCHOOL VARCHAR(2))
INSERT INTO @OTHERSCHOOLS VALUES ('10000000','MCR1010','11')
INSERT INTO @OTHERSCHOOLS VALUES ('10000000','MCR1011','14')
INSERT INTO @OTHERSCHOOLS VALUES ('10000000','MCR1012','15')
INSERT INTO @OTHERSCHOOLS VALUES ('12000000','MCR6080','19')
INSERT INTO @OTHERSCHOOLS VALUES ('13000000','MCR6090','15')
For the above sample data. Two tables. Currentschool and Otherschools.
Currentschool is the current course that a student is on including the schoolcode,
and is the main table.
OtherSchools is potentially other courses that a student can go on, in differing schools.
I need to compare the currentschool table against the otherschools table matched using the student id number, and for every different schoolcode in otherschools, it needs to return a count.
eg:
Student: OtherSchoolCount:
10000000 2 (because of 2 different school codes than than the current school)
12000000 1 (because of 1 different school code than than the current school)
13000000 blank (because not a different school code)
Is this possible?
Many thanks
M.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输出
如果 Null 确实优于 Zero,那么您可以执行此操作(或使用等效的 CTE)
哪个输出
更新:NullIF 可以用作 Case 语句的替代方案,请参阅 NULLIF() 有哪些应用?
outputs
If Null is really preferred over Zero then you can do this (or use the equivalent CTE)
Which outputs
Update: NullIF could be put to use as alternative to the Case statement see What applications are there for NULLIF()?