如何在存储过程中使用ORDER BY

时间:2016-01-09 18:46:21

标签: sql sql-server stored-procedures sql-order-by

我有以下代码:

use Northwind
go

create procedure CalcStatistics
    @year int = 0
as

if exists 
    (select * from sysobjects
  where name = 'Statistics' and type = 'U') 
  drop table Statistics

select      YEAR(ORDERS.OrderDate) As [Year],
            DATEPART(qq, OrderDate) As [Q],
            SUM (Freight) As [Freight],
into        Statistics
from        ORDERS, ORDERDETAILS
where       ORDERS.OrderID = ORDERDETAILS.OrderID
AND         YEAR(ORDERS.OrderDate) = @year
group by    YEAR(ORDERS.OrderDate),
            DATEPART(qq, OrderDate)
order by    YEAR(ORDERS.OrderDate)

exec CalcStatistics 1997
    select *
    from Statistics

我想这样做,以便查询以升序打印当年的年份和季度,但是当我尝试旧式的“按DATEPART(qq,OrderDate)订购”时,它似乎不会影响查询结果。我该如何解决这个问题,为什么我的方法不起作用?

1 个答案:

答案 0 :(得分:0)

  

我想这样做,以便查询以升序打印当年的年份和季度,

根据此声明,您需要ORDER BY中的两个键。一种方法使用别名而不是表达式。这更简单:

order by [Year], [Q]

使用日期时的另一个技巧是按日期MIN()(或MAX())订购:

order by MIN(ORDERS.OrderDate)

编辑:

我想我看到了问题。您将此数据放入名为statistics的表中,而不是查看查询本身的结果。然后你可能正在运行这样的查询:

select s.*
from statistics s;

如果是,则结果不符合要求。除非查询指定排序,否则SQL查询的结果是无序。所以:

select s.*
from statistics s
order by [Year], [Q];