私は、複数の行、1つのセルに1つの列を表示する方法を探していました。コンマで区切られた内容。複数の行に1列を表示
PROJECTIDラベル ---- --- 1200 LABEL1 1200 LABEL2 1200 LABEL3
私はこのように見えるように私のクエリの結果を希望:の代わりに、例えば
、 :事前に
ProjectID Label
———— ——–
1200 label1, label2, label3
おかげ
私は、複数の行、1つのセルに1つの列を表示する方法を探していました。コンマで区切られた内容。複数の行に1列を表示
PROJECTIDラベル ---- --- 1200 LABEL1 1200 LABEL2 1200 LABEL3
私はこのように見えるように私のクエリの結果を希望:の代わりに、例えば
、 :事前に
ProjectID Label
———— ——–
1200 label1, label2, label3
おかげ
これを行う方法はさまざまです。 1つのオプションは、複数の値のセルを別々のレコードに分割するテーブル値関数を作成することです。
ALTER FUNCTION [dbo].[Split](@RowData VARCHAR(MAX), @SplitOn VARCHAR(5))
RETURNS @RtnValue TABLE
(
Id int identity(1,1),
Data VARCHAR(MAX)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))
Return
END
一度作成、あなたの結果取得するために次の操作を行うことができます:ここでは、スプリット機能の一例である。ここ
SELECT *
FROM YourTable A
CROSS APPLY dbo.Split(Label,', ') B
テーブルを返す分割関数でSQL Serverテーブル関数を使用する
質問で助けが必要です.... – user960439
「PIVOT」はこれでまったく役に立たないでしょう – Lamak
が、私は、文字列とリターンを分割表値関数を作りましたあなたが希望通りの結果
--Create the function
CREATE FUNCTION dbo.Split(@ProjectId nvarchar(50),@String varchar(8000), @Delimiter char(1)) --Pass projectID,label and delimiter and returns table
returns @temptable TABLE (id nvarchar(50),items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(id,Items) values(@ProjectId,@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
--Calling the function
select * from dbo.split('1200',' label1, label2, label3',',') --calling teh function
create table #comma_seprate
(ProductID int,
Lable varchar(max))
declare @index int, @id int;
declare @lable varchar(max);
declare cur_comma cursor
for select ProductID, Lable from comma_seprate
open cur_comma
fetch next from cur_comma into @id, @lable
while (@@fetch_status=0)
begin
set @index=charindex(',',@lable);
while(@index>0)
begin
insert into #comma_seprate values (@id,rtrim(ltrim(left(@lable,@index-1))));
set @lable=substring(@lable,@index+1,len(@lable));
set @index=charindex(',',@lable);
end
insert into #comma_seprate values (@id, rtrim(ltrim(@lable)));
fetch next from cur_comma into @id,@lable;
end
close cur_comma;
deallocate cur_comma;
select * from #comma_seprate;
truncate table #comma_seprate;
チェックこの1 http://stackoverflow.com/questions/5493510/turning-a-comma-separated-string-into-individual-rows –