SQL ADVANCE ASHUTOSHI

2024-01-14  本文已影响0人  山猪打不过家猪

1. RANK

SELECT  [order_details_id]
      ,[order_id]
      ,[pizza_id]
      ,[quantity]
      ,[order_date]
      ,[unit_price]
      ,[total_price]
      ,[pizza_name]
      ,ROW_NUMBER() OVER(partition by order_id order by total_price desc) rank_by_id
  FROM [sales].[dbo].[pizza_sales]
image.png

2. 前后和当前行的总和

image.png
CREATE TABLE day_sales (
    ID INT,
    sale_day DATE,
    total_sale INT
);

INSERT INTO day_sales (ID, Date, Sales)
VALUES
    (1, '2022-06-22', 603),
    (2, '2022-06-21', 478),
    (3, '2022-06-20', 679),
    (4, '2022-06-19', 443),
    (5, '2022-06-18', 540),
    (6, '2022-06-17', 740),
    (7, '2022-06-16', 850),
    (8, '2022-06-15', 604),
    (9, '2022-06-14', 339),
    (10, '2022-06-13', 905);
SELECT *, SUM(Sales) OVER (ORDER BY DATE ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS Rolling_Sum
FROM [sales].[dbo].[day_sales];

3. First value和 last value

SELECT *, FIRST_VALUE(Sales) OVER(PARTITION BY State order by Date) First_sales
,LAST_VALUE(Sales) OVER(PARTITION BY State order by Date rows between unbounded preceding and unbounded following) Last_sales
FROM [sales_info_01]
image.png
  1. 移动平均值 moving average
select *, avg(sales) over(order by dateTime rows between 2 preceding and current row) as three_days_rolling_avgs,
avg(sales) over (order by dateTime rows between 6  preceding and current row) as seven_days_rolling_avgs
上一篇下一篇

猜你喜欢

热点阅读