postgresql行轉列

來源:互聯網
上載者:User

標籤:cross   cte   插入   integer   oss   data   random   交叉表   不重複   

問:怎麼分頁&&按條件&&按順序&&姓名不重複查出資料?

答:其實就是行轉列,那麼,postgresql怎麼進行轉列呢,百度了下,大概有三種寫法

 

寫法1 group by + sum + case when
select name,sum(case when zbfm=‘年齡‘ then value else 0 end) as 年齡,sum(case when zbfm=‘身高‘ then value else 0 end) as 身高,sum(case when zbfm=‘體重‘ then value else 0 end) as 體重from test group by namehaving name like ‘%1‘ and length(name)=4 order by 年齡 desc

 

寫法2用postgresql的crosstab交叉函數

crosstab(unknown, unknown) does not exist

select * fromcrosstab(
‘select name,zbfm,value from test where name like ‘‘%1‘‘ and length(name)=4‘,$$values(‘年齡‘), (‘身高‘), (‘體重‘)$$)as score(name text, 年齡 int, 身高 int, 體重 int)order by 年齡 desc

 

寫法3group by + string_agg + split_part(分組,行轉列,字元切割)
select name, split_part(split_part(temp,‘,‘,1),‘:‘,2) as 年齡,split_part(split_part(temp,‘,‘,2),‘:‘,2) as 身高,split_part(split_part(temp,‘,‘,3),‘:‘,2) as 體重from(select name, string_agg(zbfm||‘:‘||value,‘,‘) as temp from testgroup by name having name like ‘%1‘ and length(name)=4) as t order by 年齡 desc

group by + string_agg
select name, string_agg(zbfm||‘:‘||value,‘,‘) from testgroup by name having name like ‘%1‘ and length(name)=4

 其他建表語句
CREATE TABLE test(  id serial NOT NULL,  value integer,  name character varying,  zbfm character varying,  CONSTRAINT pkey PRIMARY KEY (id))
插入資料(python)
import psycopg2from random import randomconn = psycopg2.connect(database="postgres", user="postgres", password="password", host="ip", port="port")cur = conn.cursor()def insertData():    names = [‘路人甲‘, ‘王尼瑪‘, ‘唐馬儒‘]    zbfms = [‘年齡‘, ‘身高‘, ‘體重‘]    for i in range(100):        sqlstr = ‘insert into test(name, zbfm, value) values‘        for j in range(100):            for name in names:                for zbfm in zbfms:                    sqlstr += "(‘%s‘,‘%s‘,%d),"%(name+str(i*100+j),zbfm,int(100*random()))        cur.execute(sqlstr[:-1])        conn.commit()        print(i)if __name__ == ‘__main__‘:    insertData()    selectData()

 

 

參考

PostgreSQL 實現交叉表(行列轉換)的五種方法

postgresql行轉列

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.