我有这个专栏的表格:
[Student_ID],[Class_ID],[Techer_ID],[Course_ID],[Marks]
并且对于标记范围存在名称,例如: 介于0到5之间= D. 在6到10之间= C 在11到15之间= B 在16到20之间= A
现在我需要创建T-Sq l Query for Return this result message columns:
Teacher_ID|Course_ID|Count(Marks)|Count(A)| Count(B)|Count(C)|Count(D)
非常感谢您的帮助
答案 0 :(得分:2)
select Teacher_ID
, Course_ID
, count(*)
, sum(case when Marks between 16 and 20 then 1 end) as SumA
, sum(case when Marks between 11 and 15 then 1 end) as SumB
, sum(case when Marks between 6 and 10 then 1 end) as SumC
, sum(case when Marks between 0 and 5 then 1 end) as SumD
from YourTable
group by
Teacher_ID
, Course_ID
答案 1 :(得分:1)
我会使用和Andomar相同的方法,只改变总数来算这样:
select Teacher_ID
, Course_ID
, count(*)
, count(case when Marks between 16 and 20 then 1 end) as countA
, count(case when Marks between 11 and 15 then 1 end) as countB
, count(case when Marks between 6 and 10 then 1 end) as countC
, count(case when Marks between 0 and 5 then 1 end) as countD
from YourTable
group by
Teacher_ID
, Course_ID
在我看来,查询看起来更自然。
答案 2 :(得分:1)
你可以用PIVOT做到这一点。 (另请注意,Marks-to-Letter计算的这种表述比必须键入每个范围的两端的一个更安全。)
with T as (
select
Teacher_ID,
Course_ID,
case
when Marks <= 5 then 'countD'
when Marks <= 10 then 'countC'
when Marks <= 15 then 'countB'
else 'countA' end as Letter
from T
)
select
Teacher_ID,
Course_ID,
countD+countC+countB+countA as countMarks,
countA,
countB,
countC,
countD
from T pivot (
count(Letter) for Letter in ([countA],[countB],[countC],[countD])
) as P