我对SQL有点新,并且无法将此代码转换为可用于计算列的函数。这非常适合作为select语句。
select (coalesce(a.samplevalue - (
select b.samplevalue
from numericsamples b
where b.rowid = a.rowid - 1), a.samplevalue)) as Diff
from dbo.NumericSamples a
这基本上只是减去前一行值。
答案 0 :(得分:0)
具有以下定义的VIEW
对您来说不是更好吗?
我认为使用ISNULL()
代替COALESCE()
会更快一些。
我不确定我的JOIN标准是否正确。
CREATE VIEW [dbo].[Answer]
WITH SCHEMABINDING -- !Please read up about SCHEMABINDING!
AS
SELECT T1.rowid
,Result = ISNULL(T1.samplevalue - T2.samplevalue, T1.samplevalue)
FROM dbo.NumericSamples T1
JOIN dbo.NumericSamples T2 ON T1.rowid - 1 = T2.rowid
-- OR
-- JOIN dbo.NumericSamples T2 ON T1.rowid = T2.rowid -1
关于ISNULL()
vs COALESCE()
-
在这种情况下ISNULL()
似乎更快
IF OBJECT_ID('tempdb.dbo.#ISNULL') IS NOT NULL DROP TABLE #ISNULL
IF OBJECT_ID('tempdb.dbo.#COALESCE') IS NOT NULL DROP TABLE #COALESCE
DECLARE @StopW DATETIME = GETDATE()
SELECT T1.rowid
,Result = ISNULL(T1.samplevalue - T2.samplevalue, T1.samplevalue)
INTO #ISNULL
FROM dbo.NumericSamples T1
JOIN dbo.NumericSamples T2 ON T1.rowid - 1 = T2.rowid
PRINT DATEDIFF(MS, @StopW, GETDATE())
SET @StopW = GETDATE()
SELECT T1.rowid
,Result = COALESCE(T1.samplevalue - T2.samplevalue, T1.samplevalue)
INTO #COALESCE
FROM dbo.NumericSamples T1
JOIN dbo.NumericSamples T2 ON T1.rowid - 1 = T2.rowid
PRINT DATEDIFF(MS, @StopW, GETDATE())