2017-03-16 35 views
1

enter image description here年級學生對於根據不同的條件

大家好,

我有不同學科學生的痕跡。

表#Maths包含名爲a,b和c的學生數學中的標記。 與#Science和#English類似。

現在我想輸出,就好像學生在兩個科目中有超過75分的成績一樣,他會被評爲'優異'。如果他在一個科目中超過75分,其他分數超過60分,通過「,如果沒有一個科目超過75個,而一個科目少於50個,那麼他將被評爲」失敗「。

請爲我提供解決方案的結果?

感謝

回答

1
SELECT m.id, m.name, m.marks, s.marks, e.marks, 
CASE WHEN (m.marks > 75 and s.marks > 75) OR (s.marks > 75 and e.marks > 75) OR (m.marks > 75 and e.marks > 75) THEN 'Pass' 
    WHEN (m.marks > 75 and (s.marks > 60 OR e.marks > 60)) OR 
      (s.marks > 75 and (m.marks > 60 OR e.marks > 60)) OR 
      (e.marks > 75 and (s.marks > 60 OR m.marks > 60)) THEN 'Pass' 
    WHEN (m.marks < 75 and s.marks < 75 and e.marks < 75 and (m.marks < 50 or e.marks < 50 or s.marks < 50)) THEN 'Fail' 
    ELSE NULL END as Merit 
FROM #maths m 
inner join #science s 
on m.ID = s.ID 
inner join #English e 
on m.ID = e.ID 

不是很優雅,但由於只有一個需要比較少的列,我想接近它這樣

1

您可以嘗試像下面的查詢:

  • 該查詢肯定比連接更快,因爲它減少了對案例條件設置的操作
  • 業務邏輯是整潔的y作爲權重和頂部查詢條件的一部分進行封裝
  • 沒有聯接,因此速度更快。當你開始增加學生記錄和科目表時,速度會變得明顯。

查詢:

select 
    id, 
    name, 
    case 
     when sum(weightRank) >=32 then "Merit" 
     when sum(weightRank) >=20 then "Pass" 
     when sum(weightRank) <16 and count(ALL weightRank) < count(weightRank)  
     then "Fail" 
     else "N/A" 
    end as grade 
from 
(
    select id,name,'m' as subject,marks from #maths 
     union all 
    select id,name,'m' as subject,marks from #science 
     union all 
    select id,name,'m' as subject,marks from #english 
) allmarks 

-- allmarks get all records together, and is faster than joining all tables 
-- this is also extensible as subjects and students may increase 
-- and not all subjects may have marks for all students, so we will not lose data as in case of joins 

    join 
     (values (NULL,0, 50),(1,51, 60),(4,61, 75), (16,76,100) 
     as I(weightRank,lowNumber, highNumber) 

-- here we create a temp dynamic table to weight the marks 

     on 
      allmarks.marks between I.lowNumber AND I.HighNumber 

group by id,name