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