2013-06-18 75 views
0

我有一個從PIVOT表返回數據的過程。我只需要對這些數據進行排序,以便PIVOT以特定順序顯示列。我需要它們按Regions表中的「SortOrder」字段排序。這是我的腳本。我實際上並不需要返回的sortorder字段,我只需要按sortorder排序的列。任何幫助表示讚賞在SQL中對PIVOT表進行排序

CREATE TABLE #Temp 
( 
Region VARCHAR(255), 
SortOrder INT, 
Visible BIT 
) 

INSERT INTO #Temp 
SELECT R.Region, R.SortOrder, CASE WHEN (ISNULL(R_SR.RegionID,0) = 0 AND  ISNULL(R_SR_Serv.RegionID,0) = 0) THEN 0 ELSE 1 END AS Visible 
FROM ServiceRecord SR 
INNER JOIN Sites S ON SR.SiteID = S.SiteID 
INNER JOIN Regions R ON R.SiteID = S.SiteID 
LEFT OUTER JOIN lkup_Region_ServiceRecord R_SR ON R_SR.RegionID = R.RegionID AND R_SR.ServiceRecordID = SR.ServiceRecordID 
LEFT OUTER JOIN lkup_Region_ServiceRecord_Serv R_SR_Serv ON R_SR_Serv.RegionID = R.RegionID AND R_SR_Serv.ServiceRecordID = SR.ServiceRecordID 
WHERE SR.ServiceRecordID = @ServiceRecordID 
AND R.RegionID % 100 != 0 
AND SR.IsDeleted = 0 
AND SR.English = 1 
AND SR.PostedMain = 1 
ORDER BY SR.ServiceRecordID, R.SortOrder 

DECLARE @RegionList varchar(2000),@SQL varchar(max) 
SELECT @RegionList = STUFF((SELECT DISTINCT ',' + QuoteName(Region) FROM #Temp ORDER BY ',' + QuoteName(Region) FOR XML PATH('')),1,1,'') 

SET @SQL=' 
SELECT 
    A.* 
FROM 
    ( 
    SELECT 
    Region, 
    CAST(Visible AS INT) AS Visible 
    FROM #Temp 
    ) B 
    PIVOT(MAX(Visible) FOR Region IN (' + @RegionList + ')) A 
    ORDER BY SortOrder;'; 

EXEC (@SQL); 

在最初的選擇(前PIVOT),我得到如下表(這是我希望他們在樞的順序。

London and Middlesex 0 
Oxford and Norfolk 1 
Elgin 0 
Huron and Perth 1 
Grey and Bruce 0 

樞軸之後,這是我的導致

Elgin Grey and Bruce Huron and Perth London and Middlesex Oxford and Norfolk 
0   0   1    0      1 

我想在同一順序排序的列表中的樞軸(倫敦和米德爾塞克斯第一,牛津大學和諾福克2,等等)

之前顯示
+0

如果您在'select from#temp'中包含'SortOrder'列,您是否收到錯誤?結果顯示了什麼? – Taryn

+0

如果我將SortOrder添加到#temp表中,它會弄亂PIVOT,而不是返回1行,我得到多行(每個SortOrder值爲1) –

+0

您可以發佈create table語句,每個表的一些示例數據然後期望的結果?或者用您現有的結構/數據創建一個http://sqlfiddle.com? – Taryn

回答

5

如果你想最終列被隨即下令,你應該能夠添加ORDER BY SortOrder在查詢得到@regionList所以你的代碼更改爲以下:

DECLARE @RegionList varchar(2000),@SQL varchar(max) 
SELECT @RegionList = STUFF((SELECT ',' + QuoteName(Region) 
          FROM #Temp 
          GROUP BY Region, SortOrder 
          ORDER BY SortOrder --- add the SortOrder here 
          FOR XML PATH('')),1,1,'') 

您當前的代碼是訂貨該地區的數據是按字母順序排列的。您需要在此列表中實施SortOrder。

+0

謝謝,這工作完美!我試圖對那一部分進行分類,但我沒有做對。再次感謝 –

+1

很高興它正在工作,一旦你發佈數據,更容易看到如何解決它。 – Taryn