sql 精读(五) 标准 SQL窗口函数一

WITH Produce AS
 (SELECT 'kale' as item, 23 as purchases, 'vegetable' as category
  UNION ALL SELECT 'orange', 2, 'fruit'
  UNION ALL SELECT 'cabbage', 9, 'vegetable'
  UNION ALL SELECT 'apple', 8, 'fruit'
  UNION ALL SELECT 'leek', 2, 'vegetable'
  UNION ALL SELECT 'lettuce', 10, 'vegetable')

SELECT item, purchases, category, SUM(purchases)
  OVER (
    ORDER BY purchases
    ROWS BETWEEN UNBOUNDED PRECEDING AND 2 PRECEDING
  ) AS total_purchases
FROM Produce;

函数只会分析前几行。分析从分区中当前行之前的两行开始sum
在这里插入图片描述

计算移动平均值

WITH Produce AS
 (SELECT 'kale' as item, 23 as purchases, 'vegetable' as category
  UNION ALL SELECT 'orange', 2, 'fruit'
  UNION ALL SELECT 'cabbage', 9, 'vegetable'
  UNION ALL SELECT 'apple', 8, 'fruit'
  UNION ALL SELECT 'leek', 2, 'vegetable'
  UNION ALL SELECT 'lettuce', 10, 'vegetable')

SELECT item, purchases, category, AVG(purchases)
  OVER (
    ORDER BY purchases
    ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
  ) AS avg_purchases
FROM Produce

在这里插入图片描述

with 
Farm AS
 (SELECT 'cat' as animal, 23 as population, 'mammal' as category
  UNION ALL SELECT 'duck', 3, 'bird'
  UNION ALL SELECT 'dog', 2, 'mammal'
  UNION ALL SELECT 'goose', 1, 'bird'
  UNION ALL SELECT 'ox', 2, 'mammal'
  UNION ALL SELECT 'goat', 2, 'mammal')
  
 


SELECT animal, population, category, 
COUNT(*)OVER (
    ORDER BY population
    RANGE BETWEEN 1 PRECEDING AND 1 FOLLOWING
  ) AS similar_population
FROM Farm;


(goose, dog, ox, goat, duck, cat) = 4 animals between population range 0-2.
(goose, dog, ox, goat, duck, cat) = 5 animals between population range 1-3.
(goose, dog, ox, goat, duck, cat) = 5 animals between population range 1-3.
(goose, dog, ox, goat, duck, cat) = 5 animals between population range 1-3.
(goose, dog, ox, goat, duck, cat) = 4 animals between population range 2-4.
(goose, dog, ox, goat, duck, cat) = 1 animal between population range 22-24.
SELECT animal, population, category, COUNT(*)

在这里插入图片描述

posted @ 2022-08-19 22:51  luoganttcc  阅读(5)  评论(0)    收藏  举报