我有三张桌子:
Flight table
FlightId int
FlightNumber varchar(10)
FlightCapacity table
ID int
FlightIdRef int
ClassIdRef int
Capacity int
Class Table
ClassId int
Name varchar(10)
Class Table:
ClassId Name
1 Y
2 A
Flight Table
FlightId Number
1 123
2 423
FlightCapacity Table
Id FlightIdRef ClassIdref Capacity
1 1 1 10
2 1 2 20
3 2 2 10
这是一个简单的查询:
select Flight.FlightNumber,Class.Name+RTRIM(FlightCapacity.Capacity)
from Flight
inner join FlightCapacity
on Flight.FlightId=FlightCapacity.FlightIdRef
inner join Class
on FlightCapacity.ClassIdRef=Class.ClassId
但是我希望得到以下结果:(我想在一行中显示每个航班和容量的所有类别)
FlightNumber ClassNameAndCapacity
123 Y10 A20
423 Y10
答案 0 :(得分:5)
;WITH x(fn,cn) AS
(
SELECT f.FlightNumber, c.Name + RTRIM(fc.Capacity)
FROM dbo.Flight AS f
INNER JOIN dbo.FlightCapacity AS fc
ON f.FlightId = fc.FlightIdRef
INNER JOIN dbo.Class AS c
ON fc.ClassIdRef = c.ClassId
)
SELECT DISTINCT
FlightNumber = fn,
ClassNameAndCapacity = (SELECT cn + ' '
FROM x AS x2
WHERE x2.fn = x.fn
FOR XML PATH('')
)
FROM x
ORDER BY FlightNumber;