時間:2024-02-21 13:55作者:下載吧人氣:27
需求將下列表格相同id的name拼接起來輸出成一列
id | Name |
1 | peter |
1 | lily |
2 | john |
轉(zhuǎn)化后效果:
id | Name |
1 | peter;lily |
2 | john; |
實現(xiàn)方式使用 array_to_string 和 array_agg 函數(shù),具體語句如下:
string_agg(expression, delimiter) 把表達式變成一個數(shù)組
string_agg(expression, delimiter) 直接把一個表達式變成字符串
select id, array_to_string( array_agg(Name), ‘;’ ) from table group by id
補充:Postgresql實現(xiàn)動態(tài)的行轉(zhuǎn)列
在數(shù)據(jù)處理中,常遇到行轉(zhuǎn)列的問題,比如有如下的問題:
有這樣的一張表
“Student_score”表:
姓名 | 課程 | 分數(shù) |
---|---|---|
張三 | 數(shù)學(xué) | 83 |
張三 | 物理 | 93 |
張三 | 語文 | 80 |
李四 | 語文 | 74 |
李四 | 數(shù)學(xué) | 84 |
李四 | 物理 | 94 |
我們想要得到像這樣的一張表:
姓名 | 數(shù)學(xué) | 物理 | 語文 |
---|---|---|---|
李四 | 84 | 94 | 74 |
張三 | 83 | 93 | 80 |
當(dāng)數(shù)據(jù)量比較少時,我們可以在Excel中使用數(shù)據(jù)透視表pivot table的功能實現(xiàn)這個需求,但當(dāng)數(shù)據(jù)量較大,或者我們還需要在數(shù)據(jù)庫中進行后續(xù)的數(shù)據(jù)處理時,使用數(shù)據(jù)透視表就顯得不那么高效。
下面,介紹如何在Postgresql中實現(xiàn)數(shù)據(jù)的行轉(zhuǎn)列。
當(dāng)我們要轉(zhuǎn)換的值字段是數(shù)值型時,我們可以用SUM()函數(shù):
CREATE TABLE Student_score(姓名 varchar, 課程 varchar, 分數(shù) int);
INSERT INTO Student_score VALUES(‘張三’,’數(shù)學(xué)’,83);
INSERT INTO Student_score VALUES(‘張三’,’物理’,93);
INSERT INTO Student_score VALUES(‘張三’,’語文’,80);
INSERT INTO Student_score VALUES(‘李四’,’語文’,74);
INSERT INTO Student_score VALUES(‘李四’,’數(shù)學(xué)’,84);
INSERT INTO Student_score VALUES(‘李四’,’物理’,94);
select 姓名
,sum(case 課程 when ‘數(shù)學(xué)’ then 分數(shù) end) as 數(shù)學(xué)
,sum(case 課程 when ‘物理’ then 分數(shù) end) as 物理
,sum(case 課程 when ‘語文’ then 分數(shù) end) as 語文
from Student_score
GROUP BY 1
網(wǎng)友評論