sql >> Databasteknik >  >> RDS >> Sqlserver

Flera resultat för ett fält i en sammanfogad SQL-fråga

prova detta:

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

UTGÅNG:

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


  1. lagrad procedur i SQL CLR

  2. Beräknad kolumn i EF Code First

  3. Hur kan jag gå med i flera bord i symfony2?

  4. Oracle SQL-avvikelse:ANTAL(*) vs faktisk resultatuppsättning