我有这样的场景,
Studentid|Subject1|Subject2|Subject3|Subject4|Subject5|Grade
1 | 1 | 1 | 1 | 1 | 1 |
2 | 1 | 2 | 2 | 2 | 3 |
.....etc
该表显示了学生ID及其在每个项目中的排名。我想根据以下条件更新成绩栏,
1)如果所有科目排名均为1,则毕业生应为A 2)如果任何3个等级是1,而其他2个主体等级为2,那么B 3)如果任何3个等级是2,而其他2个主体等级为3,那么c
等等......像这样可以有很多条件。所以我只想知道解决方法。是否可以编写单个查询?
答案 0 :(得分:0)
您可以移动表格来计算成绩:
;with
Subject1 as (
select Studentid, 1 as SubjectCode, Subject1 as subjectResult
from your_table
),
Subject2 as (
select Studentid, 2 as SubjectCode, Subject2 as subjectResult
from your_table
),
...
Subject5 as (
select Studentid, 5 as SubjectCode, Subject5 as subjectResult
from your_table
),
subjects as (
select * from Subject1 union all
select * from Subject2 union all
...
select * from Subject5
)
select
Studentid, sum( subjectResult )
from
subjects
group by
Studentid
请注意,在最后一次选择中,您可以使用case
语句计算成绩。
您也可以稍加升级Grade
列升级:
...),
subjects as (
select * from Subject1 union all
select * from Subject2 union all
...
select * from Subject5
),
grades as (
select
Studentid, sum( subjectResult ) as grade
from
subjects
group by
Studentid
)
update t set grade = grades.grade
from your_table t
inner join grades on t.Studentid = grades.Studentid
答案 1 :(得分:0)
同意所有其他评论,这是一种存储数据的糟糕方式。但如果你陷入困境并且必须使用它,那么这样的事情可能有效:
UPDATE StudentsTable
SET StudentsTable.Grade = CASE
WHEN Tally.Total < 8
THEN 'A'
WHEN Tally.Total < 13
THEN 'B'
ELSE 'C'
END
FROM StudentsTable AS St
JOIN (
SELECT StudentID,
Subject1 + Subject2 + Subject3 + Subject4 + Subject5 AS [Total]
FROM StudentsTable
) AS Tally
ON St.StudentID = Tally.StudentID
根据需要修改CASE语句。它不漂亮,但它应该做的伎俩。
答案 2 :(得分:0)
我使用了UNPIVOT:
CREATE TABLE s
(
Studentid INT ,
Subject1 INT ,
Subject2 INT ,
Subject3 INT ,
Subject4 INT ,
Subject5 INT ,
Grade CHAR(1)
)
INSERT INTO [s] VALUES
( 1 , 1 , 1 , 1 , 1 , 1 , ''),
( 2 , 1 , 2 , 2 , 2 , 3 , '')
WITH cte AS (
SELECT u.StudentID, AVG(u.[g]) AS [grade]
from (SELECT * FROM [s]) AS [f]
UNPIVOT (g FOR [SUBJECT] IN (Subject1, Subject2, Subject3, Subject4, Subject5)) AS [u]
GROUP BY u.StudentID
)
UPDATE [s]
SET [Grade] = CASE
WHEN c.[grade] <=1 THEN 'A'
WHEN c.[grade] <=2 THEN 'B'
WHEN c.[grade] <=3 THEN 'C'
WHEN c.[grade] <=4 THEN 'D'
ELSE 'F'
END
FROM [cte] AS [c]
INNER JOIN [dbo].[s]
ON [c].StudentId = [s].[Studentid]
正如其他人所说,你的评分指标有点含糊不清,但我猜了一下。如果它不同,请根据需要进行更改。