Sql server 左侧外部联接的解决方法是添加额外的行,而不是逗号分隔的列?
我对SQL非常陌生,但热衷于学习(使用SQL server) 我的数据表有:Sql server 左侧外部联接的解决方法是添加额外的行,而不是逗号分隔的列?,sql-server,left-join,Sql Server,Left Join,我对SQL非常陌生,但热衷于学习(使用SQL server) 我的数据表有: [Keyword Branded ID] [Keyword Branded Group] google branded google bing branded bing [关键字],[来源],[访问]列 关键字列具有重复的值 [关键字]中的值示例 google google analytics how to use google ana
[Keyword Branded ID] [Keyword Branded Group]
google branded google
bing branded bing
[关键字],[来源],[访问]列
关键字列具有重复的值
[关键字]中的值示例
google
google analytics
how to use google analytics
bing
bing vs google
我的关键字定义表有:
[Keyword Branded ID] [Keyword Branded Group]
google branded google
bing branded bing
关键字列只有唯一的值,因此这将是键
我使用左外连接将[Keyword Branded Group]插入到我的数据表中,该表实际上根据每个关键字是否匹配google或bing为其分配一个标签
SELECT
ISNULL(c1.[Keyword Branded Group],'Other Branded') AS [Keyword Branded Group],
a.*
FROM [mychoice-data-b9BwZvd] a
LEFT OUTER JOIN [mychoice-keyworddims] c1 ON a.[Keyword] LIKE '%'+ c1.[Keyword Branded ID] +'%'
然而,我的问题是,这会导致额外的行,因为“bing vs google”与google和bing都匹配。这是我的理解
有人建议我可以保留数据表中的原始行数,并将新列[Keyword Branded Group]作为逗号分隔的值“Branded Google,Branded Bing”,而不是以更多行结束
遗憾的是,他们没有说更多的话,我不知道要查找哪些SQL命令!有人能帮忙吗?我只需要有人给我指出正确的方向
谢谢大家! 我能想到的最好方法是将外部联接移动到UDF中。首先创建一个函数,如
CREATE FUNCTION dbo.GetAllKeywords (@Keyword varchar(max)) RETURNS varchar(max)
AS BEGIN
DECLARE @return varchar(max)
SET @return = ''
SELECT @return = @return + ',' + [Keyword Branded Group]
FROM KeywordDefinition
WHERE @Keyword LIKE '%'+ [Keyword Branded ID] +'%'
IF (LEN(@return) > 2)
RETURN substring(@return, 2, len(@return) - 2)
ELSE
RETURN 'Other Branded'
END
然后可以将UDF作为子查询放入:
SELECT dbo.GetAllKeywords(a.Keyword), a.*
FROM [mychoice-data-b9BwZvd] a
我认为最好的方法是将外部联接移动到UDF中。首先创建一个函数,如
CREATE FUNCTION dbo.GetAllKeywords (@Keyword varchar(max)) RETURNS varchar(max)
AS BEGIN
DECLARE @return varchar(max)
SET @return = ''
SELECT @return = @return + ',' + [Keyword Branded Group]
FROM KeywordDefinition
WHERE @Keyword LIKE '%'+ [Keyword Branded ID] +'%'
IF (LEN(@return) > 2)
RETURN substring(@return, 2, len(@return) - 2)
ELSE
RETURN 'Other Branded'
END
然后可以将UDF作为子查询放入:
SELECT dbo.GetAllKeywords(a.Keyword), a.*
FROM [mychoice-data-b9BwZvd] a
很好的解决方案。您可以这样做来消除前导逗号:SET return=null;选择@return=coalesce(@return+,,)+[KeywordBrandedGroup]嗨,戴安娜,谢谢你!我现在正在尝试(星期一早上fresh brain!;-)但是我得到了一个错误“函数中包含的最后一个语句必须是返回语句”很好的解决方案。您可以这样做来消除前导逗号:SET return=null;选择@return=coalesce(@return+,,)+[KeywordBrandedGroup]嗨,戴安娜,谢谢你!我现在正在尝试(星期一早上fresh brain!;-)但是我得到一个错误“函数中包含的最后一个语句必须是返回语句”