在SQL Server 2012中使用CTE进行多行连接
输入: 所需输出: 连接每个要素行组并更新产品标签 条件:如果产品标签中不存在最后一个,则添加功能标签在SQL Server 2012中使用CTE进行多行连接,sql,sql-server,common-table-expression,Sql,Sql Server,Common Table Expression,输入: 所需输出: 连接每个要素行组并更新产品标签 条件:如果产品标签中不存在最后一个,则添加功能标签 if object_id('tempdb..#Product') is not null drop table #Product if object_id('tempdb..#ProductFeatures') is not null drop table #ProductFeatures create table #Product(Product_id int, Product_label
if object_id('tempdb..#Product') is not null drop table #Product
if object_id('tempdb..#ProductFeatures') is not null drop table #ProductFeatures
create table #Product(Product_id int, Product_label nvarchar(200))
create table #ProductFeatures(Product_id int, FeatureId int, Feature_label nvarchar(30), Feature_Value nvarchar(30))
insert into #Product(Product_id, Product_label) values
(1, 'HL Mountain Frame - Silver, 42')
,(2, 'Road-650 Black, 58')
insert into #ProductFeatures(Product_id, FeatureId, Feature_label, Feature_Value) values
(1, 1, 'Color', 'Silver')
,(1, 2, 'Height', '42')
,(1, 3, 'Widht', '12')
,(2, 1, 'Color', 'Black')
,(2, 2, 'Height', '58')
,(2, 3, 'Widht', '58')
例如,不会添加“银”,因为它存在于产品标签中
if object_id('tempdb..#Product') is not null drop table #Product
if object_id('tempdb..#ProductFeatures') is not null drop table #ProductFeatures
create table #Product(Product_id int, Product_label nvarchar(200))
create table #ProductFeatures(Product_id int, FeatureId int, Feature_label nvarchar(30), Feature_Value nvarchar(30))
insert into #Product(Product_id, Product_label) values
(1, 'HL Mountain Frame - Silver, 42')
,(2, 'Road-650 Black, 58')
insert into #ProductFeatures(Product_id, FeatureId, Feature_label, Feature_Value) values
(1, 1, 'Color', 'Silver')
,(1, 2, 'Height', '42')
,(1, 3, 'Widht', '12')
,(2, 1, 'Color', 'Black')
,(2, 2, 'Height', '58')
,(2, 3, 'Widht', '58')
问题:
如何计算CTE(而不是使用光标)?例如,您可以使用XML的
来实现这一点
Product_id Product_label
----------- ------------------------------------
1 HL Mountain Frame - Silver, 42 12
2 Road-650 Black, 58
达卡的解决方案非常好。我想提供另一种方法,使用pivot:
UPDATE P
SET P.Product_label = P2.newValue
FROM #Product AS P
INNER JOIN (
SELECT IP.Product_ID, IP.Product_label +
ISNULL(
(SELECT ' ' + PF.Feature_value AS [text()]
FROM #ProductFeatures AS PF
WHERE PF.Product_id = IP.Product_id
AND IP.Product_label NOT LIKE '%' + PF.Feature_value + '%'
FOR XML PATH('')
), '') AS newValue
FROM #Product AS IP
) AS P2
ON P.Product_ID = P2.Product_ID
注:以上解决方案未优化。。。但我提到这是另一种方式
干杯,
Maciej到@Darka,
谢谢你的帮助
只需在脚本中进行一些调整,因为我们要搜索单词:)
Sql Server游标,但我认为还有更简单的解决方案是的,没错,但OP想更新产品标签;)使用pivot会很好,但每个产品的功能集并不相同,我们不能为DynamicQueryPivot列出它们。
charindex(' ' + PF.Feature_value, IP.Product_label) = 0
SELECT IP.Product_ID, IP.Product_label +
ISNULL(
(SELECT ' ' + PF.Feature_value AS [text()]
FROM #ProductFeatures AS PF
WHERE PF.Product_id = IP.Product_id
AND charindex(' ' + PF.Feature_value, IP.Product_label) = 0
FOR XML PATH('')
), '') AS newValue
FROM #Product AS IP