【发布时间】:2016-06-29 06:14:24
【问题描述】:
我有一个表名test
first last
raj kumar
raj patel
这个表有数百行。
我有另一个名为 class 的表,其中包含 test 表中存在的所有名称以及每个主题的标记。
class_id first_name last_name subject marks
1 raj kumar physics 70
1 raj kumar chemistry 70
1 raj patel physics 80
1 raj kumar math 90
1 raj kumar computer 80
1 raj patel chemistry 90
1 raj patel math 100
2 raj kumar physics 70
2 raj kumar chemistry 70
2 raj patel physics 80
2 raj kumar math 90
2 raj kumar computer 80
2 raj patel chemistry 90
2 raj patel math 100
现在我想知道test 表格中每个学生的总分,格式如下:。
class_id raj.kumar raj.patel
1 310 270
2 n m
所以在生成的 tbale 中会有n 列数
对于这种特殊情况,我们可以写
select class_id
sum(case when first_name = 'raj' and last_name = 'Kumar' then marks else 0) as "raj.kumar",
sum(case when first_name = 'raj' and last_name = 'patel' then marks else 0)as "raj.patel"
from class
group by class_id
由于test 表中存在的学生人数不固定。所以我不想在我的查询中硬编码名字和姓氏。
我想要这样的东西,它可以计算test 表上所有学生的分数。
select class_id,
for(i = 0; i < test.size; i++)
sum(case when first_name = i.first and last_name = i.last then marks else 0 ) as i.first|| '.' ||i.last,
from class
group class_id
如何为此编写查询或存储过程 提前致谢。
我正在使用 postgresql。
【问题讨论】:
-
检查this answer。在你的情况下,它可能是
select ct('select * from test', 'class_id', 'first_name || last_name', 'marks', 'ct_cur'); fetch all in ct_cur;
标签: postgresql