0

我有一个从 PIVOT 表返回数据的过程。我只需要对这些数据进行排序,以便 PIVOT 以特定顺序显示列。我需要它们按 Regions 表中的“SortOrder”字段排序。这是我的脚本。我实际上不需要返回的 sortorder 字段,我只需要按 sortorder 排序的列。任何帮助表示赞赏

 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

我正在尝试按与枢轴之前的表格显示相同的顺序对列进行排序(首先是伦敦和米德尔塞克斯,其次是牛津和诺福克等)

4

1 回答 1

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。

于 2013-06-18T15:27:20.187 回答