我不知道这是否是最好的解决方案,但它是第一个出现在我脑海中的。同样正如人们所提到的,您不需要存储它......您可以直接从您部署的任何报告解决方案中调用此函数。懒得删除最后一个逗号,但这很简单。也可以随意调整您认为合适的日期时间格式。
CREATE TABLE dbo.Sam ([Date] DATE, Product VARCHAR(10), NewCol VARCHAR(1000))
INSERT INTO dbo.Sam
SELECT '2013/05/16','A',NULL
UNION ALL SELECT '2013/05/18','A',NULL
UNION ALL SELECT '2013/06/15','A',NULL
UNION ALL SELECT '2013/05/16','B',NULL
UNION ALL SELECT '2013/06/13','B',NULL
UNION ALL SELECT '2013/06/20','B',NULL
GO
CREATE FUNCTION dbo.fnGet4PreviousDates(@Date DATE, @Product VARCHAR(10))
RETURNS VARCHAR(1000)
AS
BEGIN
DECLARE @Out VARCHAR(1000) = ''
SELECT @Out = @Out + CONVERT(VARCHAR,[Date],112) + ','
FROM (
SELECT TOP 5 [Date]
FROM dbo.Sam
WHERE Product = @Product
AND [Date] < @Date
ORDER BY [Date] DESC
) t
RETURN @Out
END
GO
UPDATE dbo.Sam
SET NewCol = dbo.fnGet4PreviousDates([Date],Product)
SELECT * FROM dbo.Sam