我希望新列始终显示Type不为null的上一条记录的Price值。到目前为止,我可以使用当前结果,但最后一行显示的是之前2行的值。最后一行应显示0.666,而不是1.66。
我使用的是我在这里找到的示例,并添加了几行进行测试,以查看它是否始终可以正常运行以达到我的目的。
我的数据大于示例,并且可能有多个记录,其中Type不为null。似乎group_nbr
恰好返回与其他组相同的数字,这将引起问题。
我正在使用SQL Server 2017:
DECLARE @a TABLE ( number int, price money, type varchar(2),
date date, time time)
INSERT @a VALUES
(23454,1.50, NULL,'2014/02/02','07:00:02'),
(23455,1.60, NULL,'2014/02/02','07:05:02'),
(23456,0.665,'SV','2014/02/02','07:50:48'),
(23457,1.3 ,NULL,'2014/02/02','07:50:45'),
(23658,2.4 ,NULL,'2014/02/02','07:50:47'),
(23660,2.4 ,NULL,'2014/02/02','07:50:49'),
(23465,0.668,'SV','2014/02/02','07:50:46'),
(23467,0.666,'SV','2014/02/02','08:50:40'),
(23668,1.4 ,NULL,'2014/02/02','09:50:49'),
(23466,1.66, NULL,'2014/02/02','08:36:34');
; WITH a AS
(
SELECT
*,
ROW_NUMBER() OVER (ORDER BY [date], [time] ) x,
ROW_NUMBER() OVER (PARTITION BY CASE WHEN [type] IS NOT NULL THEN 1 ELSE 0 END ORDER BY [date], [time]) y
FROM
@a
), b AS
(
SELECT
*,
x - y as group_nbr,
ROW_NUMBER() OVER(PARTITION BY x-y ORDER BY x ASC) z1
FROM
a
)
SELECT
*,
CASE
WHEN [type] IS NOT NULL
THEN LAG(price, z1) OVER (PARTITION BY [type] ORDER BY x)
ELSE LAG(price, z1) OVER (ORDER BY x)
END
FROM
b
ORDER BY
x
最后一条记录应返回0.666,而不是1.66。
输出应始终返回Type不为null的行的先前价格值。
尝试一下:
WITH DataSource as
(
SELECT *
,COUNT(type) OVER (ORDER BY [date], [time] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) - MAX(IIF(type is null, 0, 1)) OVER (ORDER BY [date], [time] ROWS BETWEEN 0 FOLLOWING AND 0 FOLLOWING) groupID
FROM @a
), Groups (groupID, value) AS
(
SELECT groupID
,MAX(IIF(type is not null, price, NULL))
FROM DataSource
GROUP BY groupID
)
SELECT *
FROM DataSource A
LEFT JOIN Groups B
ON A.groupID = B.[groupID] + 1
想法是将行分为几组,然后获得该组的价格(这将是type
不为空的价格。然后,只需联接表并获得前一组的price
。