SQL 語句一行拆成多行及多行合併成一行的方法

2021-07-12 02:20:56 字數 2438 閱讀 8025

一、sql 語句對一行(單元格)資料拆分成多行    有時候我們也許對一行資料拆分成多行的操作 例如:  col1       col2 --------- ------------ 1          a,b,c 2           d,e 3           f 拆分成:  col1       col2 -------- ----- 1           a1           b 1           c 2           d 2           e 3           f  下面給出幾個經常用到的方法:  1、 sql2000用輔助表

ifobject_id('tempdb..#num') is not null

drop table #num go

select top 100id=identity(int,1,1) into #num from

syscolumnsa,syscolumns b select

a.col1,col2=substring(a.col2,b.id,charindex(',',a.col2+',',b.id)-

b.id)  from

tab a,#num b where

charindex(',',','+a.col2,b.id)=b.id --也可用substring(','+a.col2,b.id,1)=','        

2、sql2005用xml

select

a.col1,b.col2 from

(selectcol1,col2=convert(xml,''+replace(col2,',','

')+'

') from

tab)a outer

)c(v))b    3、用cte

with roy as  (   select col1,col2=cast(left(col2,charindex(',',col2+',')-1)asnvarchar(100)),   split=cast(stuff(col2+',',1,charindex(',',col2+','),'')asnvarchar(100)) from tab  union all  selectcol1,col2=cast(left(split,charindex(',',split)-1) as nvarchar(100)),   split=cast(stuff(split,1,charindex(',',split),'') asnvarchar(100)) fromroy where split>''  )    select col1,col2 from roy orderby col1option (maxrecursion 0)     二、sql 語句sql 多行資料合併為乙個單元格(行)  描述:將如下形式的資料按id欄位合併value欄位。 id    value ----- ------ 1     aa 1    bb 2     aaa 2     bbb 2    ccc 需要得到結果: id     value ------ ----------- 1      aa,bb

2      aaa,bbb,ccc  即:group by id, 求 value 的和(字串相加) */    --1、sql2000中只能用自定義的函式解決  create table tb(id int, value varchar(10)) insert into tb values(1,'aa') insert into tb values(1, 'bb') insert into tb values(2, 'aaa') insertinto tb values(2, 'bbb') insert into tb values(2, 'ccc') go   create function dbo.f_str(@id varchar(10))returns varchar(1000) as begin    declare@str varchar(1000)    select @str = isnull(@str+ ',' , '') + cast(value as varchar) from tb where id = @id   return @str end go   --呼叫函式  select id , value = dbo.f_str(id) from tbgroup by id   drop function dbo.f_strdrop table tb    --2、sql2005中的方法  create tabletb(id int, value varchar(10)) insert into tb values(1, 'aa') insert into tbvalues(1, 'bb') insert into tb values(2, 'aaa') insert into tb values(2, 'bbb')insert into tb values(2, 'ccc') go  select id, [value] = stuff((select ',' + [value] from tb t where id =tb.id for xml path('')) , 1 , 1 , '') from tb group by id

sql 多行轉成一行

例如表a id data 1 a 1 b 1 c 2 d 2 f 轉換成表b 1 a b c 2 d e smerg是自定義函式 建立乙個函式smerg create function smerg id int returns varchar 8000 asbegin declare str var...

mysql多行合併一行,一行拆分多行

資料 建表語句 drop table if exists 品牌 create table 品牌 id int 0 not null,品牌 varchar 255 character set utf8 collate utf8 general ci null default null engine i...

pandas實現多行合併一行 一行拆分多行

import pandas as pd 構造資料 data pd.dataframe 合併資料 合併前 合併後 import pandas as pd 構造資料 data pd.dataframe 拆分資料 data pinpai data 品牌 str.split expand true data...