2012-02-26 132 views
3

我有三個表:如何顯示結果查詢列,而不是逐行顯示?

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 

回答

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; 
+0

你能解釋我的第二部分。 – 2012-02-26 18:18:57

+0

FOR XML PATH是一種用來聚合值的技巧。因此,對於每個FlightNumber,它將獲取所有的c.Name + fc.Capacity值,添加一個空格,並將它們一起使用。 – 2012-02-26 18:20:43

+0

對不起。我的問題有點改變了。你能看到這篇文章嗎? (http://stackoverflow.com/questions/9460531/how-to-show-query-result-columnarin-different-columns-instead-of-row-by-row) – 2012-02-27 05:49:15