SqlServer 2005 T-SQL Query 学习笔记(8)

OVER关键字允许你去请求基于窗口的计算,也就是,整个计算在一个查询窗口完成。

 

比如下面的例子:

SELECT stor_id, ord_num, title_id,

  CONVERT(VARCHAR(10), ord_date, 120) AS ord_date, qty,

  CAST(1.*qty / sumqty * 100 AS DECIMAL(5, 2)) AS per,

  CAST(qty - avgqty AS DECIMAL(9, 2)) as diff

FROM dbo.sales,

  (SELECT SUM(qty) AS sumqty, AVG(1.*qty) AS avgqty

   FROM dbo.sales) AS AGG;

 

因为要计算平均值和总计值,并把这2个值放进一个查询窗口进行计算,这样就难免要单独进行一个平均值和总计值的查询,上面的代码就是这样。

 

但是,我们考虑下,这样进行查询,需要对一个表查询2次,这是非常低效的,能不能进行一次查询就完成上面的功能呢?

 

那么OVER关键字就可以方便我们解决这一问,比如,下面的代码:

SELECT stor_id, ord_num, title_id,

  CONVERT(VARCHAR(10), ord_date, 120) AS ord_date, qty,

  CAST(1.*qty / SUM(qty) OVER() * 100 AS DECIMAL(5, 2)) AS per,

  CAST(qty - AVG(1.*qty) OVER() AS DECIMAL(9, 2)) AS diff

FROM dbo.sales;

 

所以,类似的,我们可以把计算和普通查询连到一起,代码上显得简单,效率也更高:

SELECT stor_id, ord_num, title_id,

  SUM(qty)   OVER() AS sumqty,

  COUNT(qty) OVER() AS cntqty,

  AVG(qty)   OVER() AS avgqty,

  MIN(qty)   OVER() AS minqty,

  MAX(qty)   OVER() AS maxqty

FROM dbo.sales;

 

截止这里,上面的计算是基于整个集合的,如果我们加入PARTITION BY呢?加入这个关键字之后,我们的结果会按PARTITION BY的字段进行分组,那么SUM和AVG就只会在同一组内进行计算。

SELECT stor_id, ord_num, title_id,

  CONVERT(VARCHAR(10), ord_date, 120) AS ord_date, qty,

  CAST(1.*qty / SUM(qty) OVER(PARTITION BY stor_id) * 100

    AS DECIMAL(5, 2)) AS per,

  CAST(qty - AVG(1.*qty) OVER(PARTITION BY stor_id)

    AS DECIMAL(9, 2)) AS diff

FROM dbo.sales

ORDER BY stor_id;

 

总的一句话,OVER关键字允许更短更快的查询。

 

Technorati 标签: , ,

你可能感兴趣的:(sqlserver)