Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Vários resultados para um campo em uma consulta SQL associada


tente isso:
DECLARE @TableA  table (RowID int, Value1 varchar(5), Value2 varchar(5))
DECLARE @TableB  table (RowID int, TypeOf varchar(10))
INSERT INTO @TableA VALUES (1,'aaaaa','A')
INSERT INTO @TableA VALUES (2,'bbbbb','B')
INSERT INTO @TableA VALUES (3,'ccccc','C')
INSERT INTO @TableB VALUES (1,'wood')
INSERT INTO @TableB VALUES (2,'wood')
INSERT INTO @TableB VALUES (2,'steel')
INSERT INTO @TableB VALUES (2,'rock')
INSERT INTO @TableB VALUES (3,'plastic')
INSERT INTO @TableB VALUES (3,'paper')


;WITH Combined AS
(
SELECT
    a.RowID,a.Value1,a.Value2,b.TypeOf
    FROM @TableA                 a
        LEFT OUTER JOIN @TableB  b ON a.RowID=b.RowID

)
SELECT
    a.*,dt.CombinedValue
    FROM @TableA        a
        LEFT OUTER JOIN (SELECT
                             c1.RowID
                                 ,STUFF(
                                            (SELECT
                                                 ', ' + TypeOf
                                                 FROM Combined  c2
                                                 WHERE c2.rowid=c1.rowid
                                                 ORDER BY c1.RowID, TypeOf
                                                 FOR XML PATH('') 
                                            )
                                            ,1,2, ''
                                       ) AS CombinedValue
                             FROM Combined c1
                             GROUP BY RowID
                        ) dt ON a.RowID=dt.RowID

RESULTADO:
RowID       Value1 Value2 CombinedValue
----------- ------ ------ ------------------
1           aaaaa  A      wood
2           bbbbb  B      rock, steel, wood
3           ccccc  C      paper, plastic