oracle数据库分组,把多条数据合并成一条数据,分几个字段
程序员文章站
2022-04-08 21:26:14
...
关键函数
SELECT *
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY 分组的字段名 order by 排序的字段名) AS rnk,cc.*
FROM 表名 cc
) t
WHERE t.rnk<3
第一步:将每一组的property标上序号
select name,property,row_number() over (partition by name order by property desc) column_num from test
partition by 后面接的就应该是将要分组的字段。如果partition by property 相当于按照property分组,那么后面的列序号column_num就是1,1,1,1,1,1,1。
第二步:按name分组后按照max或min合在一条数据中:
SELECT NAME,
MAX (DECODE (column_num, 1, property)) val1,
MAX (DECODE (column_num, 2, property)) val2,
MAX (DECODE (column_num, 3, property)) val3,
MAX (DECODE (column_num, 4, property)) val4
FROM (SELECT NAME, property, ROW_NUMBER () OVER (PARTITION BY NAME ORDER BY property DESC) column_num FROM test)
GROUP BY NAME
数据就合成功了:电脑(电源、硬盘、显示器、cpu)
相机(三脚架、记忆卡、镜头)
分析一下,row_number()其实就是给每条记录返回一个数字,序号是从1开始。比如:
SELECT NAME, property, ROW_NUMBER () OVER (ORDER BY property DESC) column_num FROM test
上面的 ROW_NUMBER () OVER (PARTITION BY NAME ORDER BY property DESC,这行的意思是按照name分组再给name分组的数据进行编号。
PG 和oracle差不多,只是pg中的decode函数不能像oracle那样用,但是可以用case…when…代替。
特殊情况
如果表中数据全部存在(实际多少个字段就有多少列)
例如:
则可以
select t.prjid,max(t.procid) procid,
(select content1 from t_test where content2 = 'a' and prjid=t.prjid) content1,
(select content1 from t_test where content2 = 'b' and prjid=t.prjid) content2,
(select content1 from t_test where content2 = 'c' and prjid=t.prjid) content3,
(select content1 from t_test where content2 = 'd' and prjid=t.prjid) content4
from t_test t group by t.prjid