超前/滞后语法帮助-如何排序列?

时间:2018-11-18 00:24:37

标签: sql-server

感谢您的帮助/建议。我不清楚LAG表达式中的1,0,那是什么?为什么我的代码不起作用?

我是否必须对超前和滞后都做两个Order by

Select
    * Customer, 
    Prod, 
    day, 
    current sold, 
    date, 
    lag[current sold,1,0] OVER(PARTITION BY customer ORDER BY date DESC) as Previous Day, 
    lead[current sold,1,0] OVER(PARTITION BY customer ORDER BY date DESC) as Next Day
From 
    table1

结果:

    | PROD  | DAY | CURRENT SOLD |  date       customer |
    +-------+-----+--------------+-----------------------
    | SHIRT | M   |            2 |   1-2018       A
    | SHIRT | T   |            9 |   2-2018       B
    | SHIRT | W   |            0 |   12-2018      C
    | SHIRT | TH  |            6 |   11-2018      D
    | SHIRT | F   |            7 |   3-2018       E
    +-------+-----+--------------+--+----------------


+-------+-----+--------------+---------------+-----------+--+--------------
| PROD  | DAY | CURRENT SOLD | PREVIOUS SOLD | NEXT SOLD | date    |customer 
+-------+-----+--------------+---------------+-----------+--+---------------
| SHIRT | M   |            2 |               |         9 |  1-2018 |A
| SHIRT | T   |            9 |             2 |         0 |  2-2018 |B
| SHIRT | W   |            0 |             9 |         6 |  12-2018|C
| SHIRT | TH  |            6 |             0 |         7 |  11-2018|D
| SHIRT | F   |            7 |             6 |           |  3-2018 |E
+-------+-----+--------------+---------------+-----------+--+---------------

1 个答案:

答案 0 :(得分:0)

您可以将LAG用于上一次销售,而LEAD用于下一次销售。我为您的示例准备了样品:

--DROP TABLE #Tbl;
--DROP TABLE #Days;

CREATE TABLE #Tbl
(   
    Prod    VARCHAR(10)
    ,[DayName]  VARCHAR(2)
    ,CurrentSold    INT
);

CREATE TABLE #Days
(
    DayNumber   INT
    ,[DayName]  VARCHAR(2)
);


INSERT INTO #Days
VALUES (1,'M'),(2,'T'),(3,'W'),(4,'TH'),(5,'F');

INSERT INTO #Tbl
VALUES ('SHIRT','M',2)
,('SHIRT','T',9)
,('SHIRT','W',0)
,('SHIRT','TH',6)
,('SHIRT','F',7);


SELECT T.Prod
    ,T.DayName 
    ,T.CurrentSold
    ,LAG(CurrentSold, 1,0) OVER (ORDER BY DayNumber) AS PreviousSold
    ,LEAD(CurrentSold, 1,0) OVER (ORDER BY DayNumber) AS PreviousSold
FROM #Tbl T
INNER JOIN #Days D ON T.DayName = D.DayName;