如何在子查询中使用ORDER BY?

时间:2017-09-14 09:33:13

标签: sql-server sql-server-2012

我的查询是:

SET @query=
  N'SELECT TaskID
    ,Company
    ,TaskSource
    ,Urgency
    ,Activity
    ,StatusName
    ,RequesterMailID
    ,tsk.CreatedDate
    ,tsk.LastUpdatedDate
    ,LastUpdatedBy
    ,(DATEDIFF(DAY, dbo.GetTimeByTimeZoneId(SLAStartTime, '' NZST ''), dbo.GetTimeByTimeZoneId(SLAActualEndTime, '' NZST ''))) 
        + 1 
        - count([Pact_OEMS].[dbo].[MstHolidays](HolidayDate)) AS AgeinDaystilldate
FROM TaskMaster tsk
LEFT OUTER JOIN TrnTaskReportDetails tsr ON tsk.TaskID = tsr.intTaskId
FULL OUTER JOIN TrnSLADetails sla ON tsk.TaskID = sla.intTaskId
FULL OUTER JOIN [Pact_OEMS].[dbo].[MstHolidays] ON [Pact_OEMS].[dbo].[MstHolidays].HolidayId = sla.intTaskId
WHERE CreatedDate >= @FromDate
    AND CreatedDate <= @ToDate
    AND TaskID = @TaskID
ORDER BY tsk.CreatedDate
    ,tsk.LastUpdatedDate'

错误:

  

ORDER BY子句在视图,内联函数,派生表中无效,   子查询和公用表表达式,除非还指定了TOP或FOR XML。

如何在子查询中使用ORDER BY

1 个答案:

答案 0 :(得分:0)

尝试使用如下窗口功能

    SELECT TaskID,
       Company,
       TaskSource,
       Urgency,
       Activity,
       StatusName,
       RequesterMailID,
       tsk.CreatedDate,
       tsk.LastUpdatedDate,
       LastUpdatedBy,
       (DATEDIFF(DAY, dbo.GetTimeByTimeZoneId(SLAStartTime, '' NZST ''), dbo.GetTimeByTimeZoneId(SLAActualEndTime, '' NZST '')))+1-COUNT([Pact_OEMS].[dbo].[MstHolidays](HolidayDate)) AS AgeinDaystilldate,
       ROW_NUMBER() OVER (PARTITION BY TaskID ORDER BY tsk.CreatedDate,
                                                      tsk.LastUpdatedDate) rNO
FROM TaskMaster tsk
     LEFT OUTER JOIN TrnTaskReportDetails tsr ON tsk.TaskID = tsr.intTaskId
     FULL OUTER JOIN TrnSLADetails sla ON tsk.TaskID = sla.intTaskId
     FULL OUTER JOIN [Pact_OEMS].[dbo].[MstHolidays] ON [Pact_OEMS].[dbo].[MstHolidays].HolidayId = sla.intTaskId
WHERE CreatedDate >= @FromDate
      AND CreatedDate <= @ToDate
      AND TaskID = @TaskID

我还建议您阅读此article,因为它可以帮助您调整思路和方法。