我有一个从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
我正在尝试按照与枢轴之前的表格相同的顺序排序列(伦敦和米德尔塞克斯第一,牛津和诺福克第二等)
答案 0 :(得分: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。