Sql server 基于公共列SQL Server组合另一行

Sql server 基于公共列SQL Server组合另一行,sql-server,Sql Server,从这样的表格中: 我需要这样的结果 Result: color: red,blue size:34 查询: Declare @Attributes TABLE ( Varient Varchar(20), AllAttributes VARCHAR(MAX), GUID Varchar(50) ) INSERT INTO @Attributes select PV.Varient_Name,PVV.Varient_Value,PA.GUID FROM tblpr

从这样的表格中:

我需要这样的结果

Result:

color: red,blue

size:34
查询:

Declare @Attributes TABLE
(
    Varient Varchar(20),
    AllAttributes VARCHAR(MAX),
    GUID Varchar(50)
)

INSERT INTO @Attributes
select PV.Varient_Name,PVV.Varient_Value,PA.GUID
FROM tblproductattribute PA
INNER JOIN Product_Varients PV ON PV.Id = PA.AttributeID
INNER JOIN Product_Varient_Value PVV ON PVV.Id = PA.AttributeValue
WHERE PA.GUID='2C2E23A5-AF08-4DC0-98A7-035EE6E7A06D' --and PA.AttributeID = 1

Select * from @Attributes

这可以使用STUFF和FOR XML来完成。如果将来您发布ddl和示例数据,将更有帮助。这一次我是为你做的,所以你可以看到将来应该如何做

变体中没有字母“e”。我建议在表格中更改,否则您将永远拼写错误

declare @Something table
(
    Variant varchar(10)
    , AllAttributes varchar(10)
    , GUID uniqueidentifier
)

declare @MyGuid uniqueidentifier = newid()

insert @Something values
('color', 'red', @MyGuid)
, ('color', 'Blue', @MyGuid)
, ('size', '34', @MyGuid)

select Variant
    , STUFF((select ',' + s2.AllAttributes
            from @Something s2
            where s2.GUID = s.GUID
                and s2.Variant = s.Variant
            for XML PATH('')), 1,1 , '') as Details
from @Something s
group by s.Variant
    , s.GUID

请包括你自己的尝试,而不仅仅是说“我需要这个”。你可能想通读一遍;StackOverflow不是一个代码编写服务。欢迎来到SO,阅读这个-Hey@TylerRoper现在请检查我的查询这看起来是一个很好的解决方案。另外,感谢您对每个部分的详细解释。很好,非常感谢