2010-07-08 78 views
0

你能不能幫我如下檢查:如何查詢4個透視表

DECLARE @tblCity TABLE (CityID INT, CityName VARCHAR(100)) 
DECLARE @tblHotel TABLE (HotelID INT, HotelName VARCHAR(100)) 
DECLARE @tblTourClass TABLE (TourClassID INT, TourClass VARCHAR(100)) 
DECLARE @tblTourHotel TABLE (id INT, CityID INT, HotelID INT, TourClassID INT) 

INSERT INTO @tblCity SELECT 1, 'Phnom Penh' UNION SELECT 2, 'Siem Reap' UNION SELECT 3, 'Sihanouk Vill' 
INSERT INTO @tblHotel SELECT 1, 'City Angkor Hotel' UNION SELECT 2, 'Phnom Penh Hotel' UNION SELECT 3, 'Sihanouk Ville Hotel' UNION SELECT 4, 'New York Hotel' UNION SELECT 5, 'Pacific Hotel' UNION SELECT 6, 'Angkor Star Hotel' UNION SELECT 7, 'Khemera Angkor Hotel' UNION SELECT 8, 'Sokha beach Hotel' UNION SELECT 9, 'Costle Hotel' 
INSERT INTO @tblTourClass SELECT 1, 'Deluxe Class' UNION SELECT 2, 'Superior Class' UNION SELECT 3, 'Standard Class' 
INSERT INTO @tblTourHotel SELECT 1, 1, 2, 1 UNION SELECT 2, 2, 1, 1 UNION SELECT 3,3,3,1 UNION SELECT 4,1,4,2 UNION SELECT 5,1,5,3 UNION SELECT 6,2,6,2 UNION SELECT 7,2,7,3 UNION SELECT 8,3,8,2 UNION SELECT 9,3,9,3 

這裏的實際查詢:

SELECT CityName, [Deluxe Class], [Superior Class], [Standard Class] 
FROM 
(
SELECT tc.*, h.*, c.* 
FROM @tblTourClass tc 
    LEFT JOIN @tblTourHotel th ON tc.TourClassID = th.TourClassID 
    LEFT JOIN @tblCity c ON th.CityID = c.CityID 
    LEFT JOIN @tblHotel h ON th.HotelID = h.HotelID 
) AS sourcetable 
PIVOT 
( MAX(HotelName) 
    FOR TourClass IN ([Deluxe Class], [Superior Class], [Standard Class]) 
) AS pivottable 
WHERE CityName IS NOT NULL 

而且結果:

City Name  Deluxe Class   Superior First Standard 
Siem Reap  City Angkor Hotel  NULL NULL NULL 
Phnom Penh  Phnom Penh Hotel  NULL NULL NULL 
Sihanouk Vill Sihanouk Ville Hotel NULL NULL NULL 

但我想要顯示爲波紋管:

City Name Deluxe Class  Superior   Standard 
Siem Reap CityAngkor Hotel Angkor Star Hotel Khemera Angkor Hotel 
Phnom Penh Phnom Penh Hotel New York Hotel  Pacific Hotel 
Sihanouk Sihanouk Hotel Sokha beach Hotel Costle Hotel 

你能幫我做如何顯示如上。

千恩萬謝

+0

什麼數據庫?什麼版本?你能描述一下你想要達到什麼嗎? – 2010-07-08 05:13:34

+0

SQL Server 2005 – Kosaly 2010-07-08 06:34:04

回答

1

試試這個:

SELECT 
    pvt.CityName, 
    pvt.[Deluxe Class], 
    pvt.[Superior Class], 
    pvt.[Standard Class] 
FROM ( 
SELECT 
    c 
    .CityName, 
    h.HotelName, 
    tc.TourClass 
FROM @tblCity c 
LEFT JOIN @tblTourHotel th ON c.CityID = th.CityID 
LEFT JOIN @tblHotel h ON th.HotelID = h.HotelID 
LEFT JOIN @tblTourClass tc ON th.TourClassID = tc.TourClassID 
) t 
PIVOT (
    MAX(HotelName) 
    FOR TourClass IN ([Deluxe Class], [Superior Class], [Standard Class]) 
) AS pvt 

它看起來像使用SELECT tc.*, h.*, c.*,總價值的計算就成了問題。但我也重新排列了查詢,以便@tblCity是所有左連接的基礎。

+0

尊敬的先生 非常感謝您的幫助,問題已解決。 – Kosaly 2010-07-08 06:35:35

+0

你好,多一個 我想在asp.net上顯示,所以我該怎麼做。 – Kosaly 2010-07-08 07:08:33

+0

我會將此作爲一個新問題來說明你需要完成什麼。 – 8kb 2010-07-08 15:47:27