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