选择不同的案例中的ORDER BY问题

时间:2014-03-13 05:20:39

标签: sql sql-server-2008

SELECT DISTINCT
    CAST(dpt.TrackId AS varchar(20)) + ' , ' + CONVERT(VARCHAR(19), dpt.CreatedDate) AS TrackId  
FROM         
    ExcelUtilityTemplate 
INNER JOIN        
    DataImportProcessTracker dpt ON ExcelUtilityTemplate.TemplateId = dpt.TemplateId        
INNER JOIN
    TA_JDSU..Employee_Temp et ON et.TrackId = dpt.TrackId        
WHERE     
    (ExcelUtilityTemplate.ClientId = 'e0a94231-3265-4277-9cc3-236d9a2ead49' 
     AND et.RowStatus = 1) 
ORDER BY 
    dpt.CreatedDate desc

我的上述查询引发以下错误:

  

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

我想根据CreatedDate

对记录进行排序

希望快速回复。感谢

2 个答案:

答案 0 :(得分:1)

按如下方式修改您的查询:

  SELECT distinct  Cast(dpt.TrackId as varchar(20)) +' , '+ CONVERT(VARCHAR(19),dpt.CreatedDate) as TrackId ,dpt.CreatedDate
    FROM         ExcelUtilityTemplate INNER JOIN        
                          DataImportProcessTracker dpt ON ExcelUtilityTemplate.TemplateId = dpt.TemplateId        
                          inner join TA_JDSU..Employee_Temp et on et.TrackId=dpt.TrackId        
    WHERE     (ExcelUtilityTemplate.ClientId = 'e0a94231-3265-4277-9cc3-236d9a2ead49' and et.RowStatus=1) order by dpt.CreatedDate desc

<强>解释

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

当你使用distinct时,选择和按某个字段排序。然后,该字段应包含在您的select子句

希望这会有所帮助..

答案 1 :(得分:1)

您需要按照与DISTINCT开启时相同的值进行排序,否则您最终可能会为每一行订购多个值;

SELECT distinct CAST(dpt.TrackId as varchar(20)) +' , '+ 
                CONVERT(VARCHAR(19),dpt.CreatedDate) as TrackId  
FROM ExcelUtilityTemplate 
INNER JOIN DataImportProcessTracker dpt 
  ON ExcelUtilityTemplate.TemplateId = dpt.TemplateId        
INNER JOIN TA_JDSU..Employee_Temp et 
  ON et.TrackId=dpt.TrackId        
WHERE (ExcelUtilityTemplate.ClientId = 'e0a94231-3265-4277-9cc3-236d9a2ead49' 
  AND et.RowStatus=1) 
ORDER BY CAST(dpt.TrackId as varchar(20)) +' , '+ 
                CONVERT(VARCHAR(19),dpt.CreatedDate) DESC