sql:按日期排序

时间:2017-03-08 13:44:43

标签: sql

我想按日期订购表格,但我的查询显示错误:

  

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

我的查询:

    select intervaldate, [M1], [M2], [M3], [M4], [M5], [M6], [M7], [M8]
    from 
    (select intervaldate,amount, name from (Select tSystem.Name, IntervalCount.IntervalDate, 
    sum(case when CounterName = 'Prod' then calculationUnits else 0 end) as Amount from IntervalCount, tsystem where 

    IntervalCount.intervaldate between '2017-03-06 00:00:00.000' and '2017-03-08 00:00:00.000' and IntervalCount.systemid =tsystem.id 

    group by tSystem.Name, IntervalCount.Intervaldate
order by IntervalCount.Intervaldate asc
    ) as T3) as T1 
    pivot 
    (sum (amount)
    for name in ([M1], [M2], [M3], [M4], [M5], [M6], [M7], [M8])

    ) as t2

我如何通过IntervalDate订购?

1 个答案:

答案 0 :(得分:3)

正如消息错误所述,您无法在派生表中使用order by(在您的情况下)。 您应该将order by替换为查询结尾,如下所示

    select intervaldate, [M1], [M2], [M3], [M4], [M5], [M6], [M7], [M8]
    from 
    (select intervaldate,amount, name from (Select tSystem.Name, IntervalCount.IntervalDate, 
    sum(case when CounterName = 'Prod' then Units else 0 end) as Amount from IntervalCount, tsystem where 

    IntervalCount.intervaldate between '2017-03-06 00:00:00.000' and '2017-03-08 00:00:00.000' and IntervalCount.systemid =tsystem.id 

    group by tSystem.Name, IntervalCount.Intervaldate
order by IntervalCount.Intervaldate asc
    ) as T3) as T1 
    pivot 
    (sum (amount)
    for name in ([M1], [M2], [M3], [M4], [M5], [M6], [M7], [M8])

    ) as t2
    order by Intervaldate asc