我正在使用SQL Server 2014。
我有一张桌子:
CREATE TABLE [dbo].tmpJobStatus
(
[JobNum] [INT] NOT NULL,
[Action] [VARCHAR](8) NULL,
[ActionDate] [DATE] NULL,
[SeqNum] [INT] NULL
) ON [PRIMARY]
我有一些数据:
INSERT INTO tmpJobStatus ([JobNum], [Action], [ActionDate], [SeqNum])
VALUES (12345, N'TEL', CAST(N'2019-07-05' AS Date), 19),
(12345, N'AL2', CAST(N'2019-07-02' AS Date), 15),
(12345, N'AL1', CAST(N'2019-05-28' AS Date), 8),
(12345, N'TELA', CAST(N'2019-05-16' AS Date), 2),
(6789, N'MAIN', CAST(N'2019-11-04' AS Date), 25),
(6789, N'MAIN', CAST(N'2019-11-04' AS Date), 21),
(6789, N'TEL', CAST(N'2019-10-29' AS Date), 20),
(6789, N'MACO', CAST(N'2019-10-28' AS Date), 13),
(6789, N'UCIN', CAST(N'2019-09-12' AS Date), 11)
如果我对一个作业使用以下内容执行LAG
和LEAD
,则会得到所需的结果:
SELECT
[JobNum],
[ActionDate],
[SeqNum],
LAG(p.[Action]) OVER (ORDER BY p.[JobNum],p.[SeqNum]) FromActionCode,
LEAD(p.[Action]) OVER (ORDER BY p.[JobNum],p.[SeqNum]) ToActionCode
FROM
[tmpJobStatus] p
WHERE
[JobNum] = 6789
ORDER BY
p.[JobNum], p.[SeqNum] DESC
结果:
JobNum ActionDate SeqNum FromActionCode ToActionCode
6789 2019-11-04 25 MAIN NULL
6789 2019-11-04 21 TEL MAIN
6789 2019-10-29 20 MACO MAIN
6789 2019-10-28 13 UCIN TEL
6789 2019-09-12 11 NULL MACO
请注意,第一个FromActionCode和LastToCode为NULL,这是正确的。
但是,如果我查看所有记录,就会搞砸了:
JobNum ActionDate SeqNum FromActionCode ToActionCode
6789 2019-11-04 25 MAIN TELA
6789 2019-11-04 21 TEL MAIN
6789 2019-10-29 20 MACO MAIN
6789 2019-10-28 13 UCIN TEL
6789 2019-09-12 11 NULL MACO
12345 2019-07-05 19 AL2 NULL
12345 2019-07-02 15 AL1 TEL
12345 2019-05-28 8 TELA AL2
12345 2019-05-16 2 MAIN AL1
我想念什么?
答案 0 :(得分:3)
您尝试使用PARTITION
SELECT [JobNum], [ActionDate], [SeqNum],
LAG(p.[Action]) OVER (PARTITION BY p.[JobNum] ORDER BY p.[SeqNum]) FromActionCode,
LEAD(p.[Action]) OVER (PARTITION BY p.[JobNum] ORDER BY p.[SeqNum]) ToActionCode
FROM [tmpJobStatus] p
ORDER BY p.[JobNum],p.[SeqNum] desc