我有一個從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,等等)
之前顯示
如果您在'select from#temp'中包含'SortOrder'列,您是否收到錯誤?結果顯示了什麼? – Taryn
如果我將SortOrder添加到#temp表中,它會弄亂PIVOT,而不是返回1行,我得到多行(每個SortOrder值爲1) –
您可以發佈create table語句,每個表的一些示例數據然後期望的結果?或者用您現有的結構/數據創建一個http://sqlfiddle.com? – Taryn