(此示例适用于 SQL Server)
如果将初始结果保存在表或临时数据结构中,则可以在 SQL 中执行此操作。如果您进行子查询,您可以用前一行的费率减去该行的费率。这是按日期计算的,因此您为给定的患者/医生选择了 MAX(日期),无论(主键?)是什么。在这种情况下,我使用“PatientID”来识别患者。见下文:
--Assume your values are saved in a table or other temp table
DECLARE @tmp TABLE (PatientID int, Interview_Date date, Avg_Alcohol_Use_Month decimal (4,2), Avg_Drug_Use_Month decimal (4,2))
INSERT INTO @tmp
VALUES
(1, '2017-01-30', 1.63, 1.34)
,(2, '2017-06-30', 2.58, 0.80)
,(1, '2017-03-01', 1.54, 1.23)
,(1, '2017-07-02', 3.21, 0.20)
,(2, '2017-08-23', 2.10, 4.52)
SELECT PatientID
,Interview_Date
,Avg_Alcohol_Use_Month
,Avg_Drug_Use_Month
,Avg_Alcohol_Use_Month
-
(SELECT Avg_Alcohol_Use_Month
FROM @tmp T2
WHERE T2.PatientID = T1.PatientID
AND T2.Interview_Date = (SELECT MAX(Interview_Date)
FROM @tmp T3
WHERE T3.Interview_Date < T1.Interview_Date
AND T3.PatientID = T1.PatientID
-- or whatever PK that makes the row unique for the patient.
)
) AS [Alcohol Use Rate change]
,Avg_Drug_Use_Month
-
(SELECT Avg_Drug_Use_Month
FROM @tmp T2
WHERE T2.PatientID = T1.PatientID
AND T2.Interview_Date = (SELECT MAX(Interview_Date)
FROM @tmp T3
WHERE T3.Interview_Date < T1.Interview_Date
AND T3.PatientID = T1.PatientID
-- or whatever PK makes the row unique for the patient.
)
) AS [Drug Use Rate change]
FROM @tmp T1
ORDER BY PatientID, Interview_Date
使用这样的查询作为 SSRS 的数据集。