2012-03-10 51 views
2

我有一个表通过该柱:AVG和从一个列计数

[Student_ID],[Class_ID],[Techer_ID],[Course_ID],[Marks] 

和用于标记的范围,例如存在名称: 之间0至5 = d 6至10 = C 之间11至15 = B 之间16到20 = A

现在我需要返回创建T-呎升查询此结果消息列:

Teacher_ID|Course_ID|Count(Marks)|Count(A)| Count(B)|Count(C)|Count(D) 

非常感谢您的帮助

回答

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
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

你可以用PIVOT做到这一点。 (还要注意的是,标记到字母计算的这种表述比每个范围的两端都必须键入的表述更安全)。

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