这里我来演示下在postgresql里面如何实现交叉表的展示,至于什么是交叉表,我就不多说了,度娘去哦。原始表数据如下:t_girl=#select*fromscore;name|subject&n.
这里我来演示下在postgresql里面如何实现交叉表的展示,至于什么是交叉表,我就不多说了,度娘去哦。
原始表数据如下:
t_girl=# select * from score; name | subject | score -------+---------+------- lucy | english | 100 lucy | physics | 90 lucy | math | 85 lily | english | 95 lily | physics | 81 lily | math | 84 david | english | 100 david | physics | 86 david | math | 89 simon | english | 90 simon | physics | 76 simon | math | 79(12 rows)time: 2.066 ms想要实现以下的结果:
name | english | physics | math -------+---------+---------+------ simon | 90 | 76 | 79 lucy | 100 | 90 | 85 lily | 95 | 81 | 84 david | 100 | 86 | 89大致有以下几种方法:
1、用标准sql展现出来
t_girl=# select name, t_girl-# sum(case when subject = 'english' then score else 0 end) as english,t_girl-# sum(case when subject = 'physics' then score else 0 end) as physics,t_girl-# sum(case when subject = 'math' then score else 0 end) as math t_girl-# from scoret_girl-# group by name order by name desc; name | english | physics | math -------+---------+---------+------ simon | 90 | 76 | 79 lucy | 100 | 90 | 85 lily | 95 | 81 | 84 david | 100 | 86 | 89(4 rows)time: 1.123 ms
2、用postgresql 提供的第三方扩展 tablefunc 带来的函数实现
以下函数crosstab 里面的sql必须有三个字段,name, 分类以及分类值来作为起始参数,必须以name,分类值作为输出参数。
t_girl=# select *from crosstab('select name,subject,score from score order by name desc',$$values ('english'::text),('physics'::text),('math'::text)$$)as score(name text, english int, physics int, math int); name | english | physics | math -------+---------+---------+------ simon | 90 | 76 | 79 lucy | 100 | 90 | 85 lily | 95 | 81 | 84 david | 100 | 86 | 89(4 rows)time: 2.059 ms
3、用postgresql 自身的聚合函数实现
t_girl=# select name,split_part(split_part(tmp,',',1),':',2) as english,t_girl-# split_part(split_part(tmp,',',2),':',2) as physics,t_girl-# split_part(split_part(tmp,',',3),':',2) as matht_girl-# fromt_girl-# (t_girl(# select name,string_agg(subject||':'||score,',') as tmp from score group by name order by name desct_girl(# ) as t; name | english | physics | math -------+---------+---------+------ simon | 90 | 76 | 79 lucy | 100 | 90 | 85 lily | 95 | 81 | 84 david | 100 | 86 | 89(4 rows)time: 2.396 ms