[MSSQL]SQL Server善用LOG10 和POWER 函數

MSDN聯機註解:LOG10 和POWER 函數是彼此反向關聯。例如,10^ LOG10(n) = n。
只有一個值的轉換時沒問題,以下測測結果集。

;WITH C
AS
(
SELECT number FROM master..spt_values WHERE number BETWEEN 1 AND 10 AND type IN(‘P’)
)
SELECT POWER(10,SUM(LOG10(number))) FROM C

/*
3628800
*/
–用一個變量驗證一下

DECLARE @i INT
SET @i=1
;WITH C
AS
(
SELECT number FROM master..spt_values WHERE number BETWEEN 1 AND 10 AND type IN(‘P’)
)
SELECT @i=@i*number FROM C

SELECT @i

/*
3628800
*/

–相同正確

go

–改變一下測試數據

DECLARE @T TABLE(number int)
INSERT @T
select 1 UNION ALL
SELECT 2 UNION ALL
SELECT 4

SELECT POWER(10,SUM(LOG10(number))) FROM @T
/*
7
*/
DECLARE @i INT
SET @i=1
SELECT @i=@i*number FROM @T
SELECT @i

/*
8
*/
–結果不正確了
反而用自然對數的基底時,更準確。

SELECT EXP(SUM(LOG(number))) FROM @T 
/*
8
*/
結論:在結果集乘積時,別用Log10對數,還是自定議函數穩定。

你可能感兴趣的:([MSSQL]SQL Server善用LOG10 和POWER 函數)