我有以下数据,我想只显示3行(表1中每个Table1Id有1行),但有些id在table2中有多个条目,在显示数据时会创建一个新行,但我想要组合表2将数据分成表1中的单行。
Table 1 Table 2
Table1Id Name State table2Id Table1Id City
1 Bart Idaho 1 1 Boise
2 Jenny Utah 2 2 Salt Lake
3 Jill Arizona 3 3 Phoenix
4 3 Yuma
Select * From Table1 FULL OUTER JOIN Table2 ON Table1.TableId = Table2.Table1Id
So far, it displays 4 rows like this:
Name State City
1.Bart Idaho Boise
2. Jenny Utah Salt Lake
3. Jill Arizona Phoenix
4. Jill Arixona Yuma
I want it to display 3 rows like this (with my gridview of course)
Name State City
1.Bart Idaho Boise
2. Jenny Utah Salt Lake
3. Jill Arizona Phoenix Yuma
答案 0 :(得分:0)
与此question类似,您可以将STUFF
和XML PATH
与GROUP BY
...
SELECT
[ID],
[NAME],
[STATE],
STUFF((
SELECT ', ' + [City] + ':' + CAST([Value] AS VARCHAR(MAX))
FROM #YourTable
WHERE (ID = Results.ID)
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
,1,2,'') AS NameValues
FROM #YourTable Results
GROUP BY ID
由于这更像是一个显示问题,所以通常在前端而不是后端更好。