0

我有这样的场景,

 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

等等......像这样的许多情况可以来。所以我只想知道解决方法。

是否可以编写单个查询?

4

3 回答 3

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
于 2012-07-18T14:29:31.570 回答
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 语句。它不漂亮,但它应该可以解决问题。

于 2012-07-18T14:58:52.953 回答
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]

正如其他人所说,你的评分指标有点模棱两可,但我猜了一下。如果不同,请根据需要进行更改。

于 2012-07-18T18:12:33.773 回答