0

我对 SQL 有点陌生,并且无法将此代码转换为可用于计算列的函数。这非常适合作为选择语句。

select (coalesce(a.samplevalue - (
    select b.samplevalue 
    from numericsamples b 
    where b.rowid = a.rowid - 1), a.samplevalue)) as Diff 
from dbo.NumericSamples a

这基本上只是减去前一行的值。

4

1 回答 1

0

具有以下定义的 aVIEW对您来说不是更好吗?使用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())
于 2013-01-05T06:54:18.917 回答