So trennen Sie Spaltenwerte mit Komma
Ich habe einen TischGrouping
Groupid (PK), Sensorid (FK) vonSensor
Tabelle. UndSensor
Tabelle hat Unitsid als Fremdschlüsselreferenz. Daher habe ich diese Abfrage verwendet, um alle Spalten aus drei Tabellen abzurufen:
Select * from Grouping
left join Sensors on Grouping.SensorID = Sensors.SensorID
left joinUnits on Grouping.UnitsID = Units.UnitsID
Ausgabe:
Group Unit Sensor
G1 U1 S1
G1 U2 S2
G1 U1 S4
G1 U1 S3
G1 U2 S5
G2 U1 S7
Mein Problem ist, dass ich die Ausgabe wie folgt haben möchte:
G1 U1 S1,S3,S4
G1 U2 S2,S5
G2 U1 S7
Wie erhalte ich diese Ausgabe aus der Tabelle "Gruppierung"?
WITH CTE
AS
(
Select * fromGrouping
left join Sensors on Grouping.SensorID = Sensors.SensorID
left join Units onGrouping.UnitsID = Units.UnitsID
)
SELECT
t1."Group",
t1.Unit ,
STUFF((
SELECT ', ' + t2.Sensor
FROM Grouping t2
WHERE t2."Group" = t1."Group"
AND t2.Unit = t1.Unit
FOR XML PATH (''))
,1,2,'') AS Sensors
FROM Grouping t1
GROUP BY t1."Group", t1.Unit;
Dies funktioniert nicht, da die Gruppierungstabelle nur sensorId und unitsId enthält und daher einen ungültigen Spaltenfehler ausgibt.