我在SQL Server中有一个表Kwd_UploadRecored
:
ID Primary_Kwd Sec_Kwd Main_Kwd
1 Man,One Man,architecture,Boy Arrival,Sigle Man , Business Man ,Male aspirations,One Person
2 Woman,attire,Girl Girl,Girls,Female,Blueprint,Carrying, Teenage Girl,Only Girls
3 Grand father,Man,caucasian appearance cheerful, Family,Fatherhood,Family Member, Male Parent,
4 Baby ,clothes,color image growth,Babies,Child,Happiness Children,Toddlers,differential focus,
我想从Primary_Kwd
,Sec_kwd
,Main_kwd
中选择与此类似的数据:
Kwds
man
one man
architecture
boy
arrival
Single man
Business man
Male
.
.
etc
我使用以下代码,但这仅适用于一列
SELECT DISTINCT
Split.a.value('.', 'VARCHAR(100)') data
FROM
(SELECT
#temp.PM_AssetID,Cast ('<M>'
+ replace(Replace(#temp.Primary_kwd, ',', '</M><M>'),'&','&')
+ '</M>' AS XML) AS Data
FROM #temp) AS A
CROSS APPLY
Data.nodes ('/M') AS Split(a)
DROP TABLE #temp
请帮我解决这个问题。提前谢谢。
答案 0 :(得分:3)
您可以使用UNION
删除重复项:
;WITH CtePrimary AS(
SELECT
LTRIM(RTRIM(s.Item)) AS Item
FROM Kwd_UploadRecorded k
CROSS APPLY dbo.DelimitedSplit8K(k.Primary_Kwd, ",") s
),
CteSec AS(
SELECT
LTRIM(RTRIM(s.Item)) AS Item
FROM Kwd_UploadRecorded k
CROSS APPLY dbo.DelimitedSplit8K(k.Sec_Kwd, ",") s
),
CteMain AS(
SELECT
LTRIM(RTRIM(s.Item)) AS Item
FROM Kwd_UploadRecorded k
CROSS APPLY dbo.DelimitedSplit8K(k.Main_Kwd, ",") s
)
SELECT * FROM CtePrimary UNION
SELECT * FROM CteSec UNION
SELECT * FROM CteMain
根据Turophile的评论,你可以通过在分割它们之前首先连接UNION
来摆脱kwd
。
SELECT DISTINCT
LTRIM(RTRIM(s.Item)) AS Item
FROM Kwd_UploadRecorded k
CROSS APPLY dbo.DelimitedSplit8K(k.kPrimary_kwd + ',' + k.Sec_kwd + ',' + k.Main_kwd, ",") s
答案 1 :(得分:0)
您必须创建Spit
功能并使用Cross Aplly
主要查询
SELECT Distinct T.ID
,S.Data
FROM Kwd_UploadRecored AS T
CROSS APPLY dbo.Split(isnull(T.Primary_Kwd+ ',','') + isnull(Sec_Kwd+',','') + ',' + isnull(Main_Kwd+',' ,'') ) AS S
WHERE S.Value > ''
拆分功能代码
CREATE FUNCTION [dbo].[Split]
(
@RowData nvarchar(MAX),
@SplitOn nvarchar(5)
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data varchar(8000)
)
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
答案 2 :(得分:0)
你能试试吗
Select *
from #temp
cross apply fnSplit(Primary_Kwd,',')a
where a.value > ''
union all
Select b.value
from #temp
cross apply fnSplit(Sec_Kwd,',')b
where b.value > ''
union all
Select c.value
from #temp
cross apply fnSplit(Main_Kwd,',')c
where c.Value > ''