为XML添加order by抛出错误

时间:2017-01-16 12:35:51

标签: sql xml sql-server-2008 tsql

这是我的实际查询

SELECT 
    aces.ProductID,'<p>' +  
    Replace(STUFF((SELECT DISTINCT ', ' + CAST(A.year AS VARCHAR(4)) + ' ' + A.make + ' ' + A.model + ' ' + A.enginebase_new 
                   FROM ACES_Data A 
                   WHERE A.ProductID = aces.ProductID 
                   FOR XML PATH('')), 1, 1, ''), ',', '<br>')
           + '</p><p>' + i.[Subline Code] + '<br>' + i.[Subline Name] + '</p>' AS FullDescription 
FROM
    ACES_Data aces 
LEFT OUTER JOIN
    InventoryPricing i ON aces.part_number = i.PART  
WHERE 
    aces.ProductID IS NOT NULL
    AND aces.MakeModelMappingID IS NOT NULL
GROUP BY 
    aces.ProductID, i.[Part Description], i.[Subline Code], i.[Subline Name]

现在在XML之前添加order by会抛出错误。

请查看以下更新的查询

 SELECT 
    aces.ProductID,'<p>' +  
    Replace(
            STUFF
                (
                    (
                        SELECT 
                            distinct ', ' + Cast(A.year as varchar(4)) + ' ' + A.make +' ' + A.model + ' ' + A.enginebase_new 
                        FROM 
                            ACES_Data A 
                        Where 
                            A.ProductID=aces.ProductID 
                        order by A.make,A.year asc
                        FOR XML PATH('') 
                    ),1,1,'')
                    ,',',
                    '<br>'
                )
    + '</p><p>' + i.[Subline Code] + '<br>'+ i.[Subline Name] + '</p>' As FullDescription 
from ACES_Data aces 
Left outer join InventoryPricing i 
on aces.part_number = i.PART  
where aces.ProductID is not null 
and aces.MakeModelMappingID is not null  
Group By aces.ProductID,i.[Part Description],i.[Subline Code],i.[Subline Name]

插入

Where A.ProductID=aces.ProductID **order by A.make,A.year asc**  FOR XML PATH('') 

它给了我错误

  

如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。

1 个答案:

答案 0 :(得分:0)

enginebase_new&amp; model不属于Order byDISTINCT无法使用Select

使用Group by代替DISTINCT删除重复项

SELECT ', ' + Cast(A.year AS VARCHAR(4)) + ' ' + A.make
       + ' ' + A.model + ' ' + A.enginebase_new
FROM   ACES_Data A
WHERE  A.ProductID = aces.ProductID
GROUP  BY A.year,
          A.make,
          A.model,
          A.enginebase_new
ORDER  BY A.make,
          A.year ASC
FOR XML PATH('')