计算表

时间:2016-11-18 15:35:45

标签: sql postgresql

我有一张桌子(stu_grades),用于存储学生数据及其所在中心的成绩

我想了解多少次,例如该表中的每个学生在任何中心获得“A”然后“B”等

stu_grades

 stu_ID|grade1|grade2|Grade3|center
    1        A      A     C    1
    2        B      B     B    2
    3        C      C     A    1
    1        C      A     C    2

同一个学生可以在同一个级别甚至不同年级,相同或不同中心的桌子上出现不止一次

我特别想检查等级出现次数超过3次或更多次以及它们存在多少厘米

所以最终输出应该是:

Stu_ID|Grade|Count|centercount
1       A      3       2 (As they accquired 'A' from 2 centres)
1       C      3       2 
2       B      3       1 (As they only exist in 1 centre)
3       C      2       1 
3       A      1       1

2 个答案:

答案 0 :(得分:1)

这是一种使用union all将不同成绩拆分为一列然后进行聚合的方法。

select stu_id,grade,count(*) cnt 
from (
select stu_id,grade_1 grade from stu_grades
union all
select stu_id,grade_2 grade from stu_grades
union all
select stu_id,grade_3 grade from stu_grades
) t
group by stu_id,grade

答案 1 :(得分:0)

这应该满足您的要求:

SELECT [Stud_ID], Grade, count(*) as GradeCount FROM
  (SELECT [Stud_ID],Grade1 as Grade from [Stud_Details]
   UNION ALL
   SELECT [Stud_ID],Grade2 as Grade from [Stud_Details]
   UNION ALL
   SELECT [Stud_ID],Grade3 as Grade from [Stud_Details]) AS T
   GROUP BY T.[Stud_ID],T.Grade
   ORDER BY T.[Stud_ID]

<强>更新

您可以在HAVING之后使用GROUP BY获取大于 3 gradeCount

SELECT [Stud_ID], Grade, count(*) as GrdCountStud FROM
  (SELECT [Stud_ID],Grade1 as Grade from [Stud_Details]
   UNION ALL
   SELECT [Stud_ID],Grade2 as Grade from [Stud_Details]
   UNION ALL
   SELECT [Stud_ID],Grade3 as Grade from [Stud_Details]) AS T
   GROUP BY T.[Stud_ID],T.Grade
     HAVING COUNT(*) > 3   
   ORDER BY T.[Stud_ID]