除法 Dividend / Divisor
製作報表時,常常需要用百分比表示,因此會利用到除法來進行計算,使用除法有兩件注意事項
- 分母不得為零
SELECT 1.0 / 0 -- 模擬除以零錯誤
- NULLIF() 說明:
- 語法:NULLIF ( express1 , express2 )
- 傳回類型:當 express1 等於 express2 時,會傳回 NULL;當 express1 不等於 express2 時,傳回 express1 值。
SELECT
1.0 / NULLIF(T.[分母], 0) AS [利用 NULLIF],
1.0 / CASE WHEN T.[分母] = 0 THEN NULL ELSE T.[分母] END AS [利用 CASE WHEN 1],
CASE WHEN T.[分母] = 0 THEN NULL ELSE 1.0 / T.[分母] END AS [利用 CASE WHEN 2],
CASE WHEN T.[分母] = 0 THEN 0 ELSE 1.0 / T.[分母] END AS [利用 CASE WHEN 3],
CASE WHEN T.[分母] = 0 THEN '分母為0' ELSE '分母不為0' END AS [文字敘述]
FROM
(
SELECT 0 AS [分母]
UNION ALL
SELECT 3
) T
- 整數相除
SELECT
T.[算式],
T.[結果]
FROM
(
SELECT '10 / 3' AS [算式] , 10 / 3 AS [結果]
UNION ALL
SELECT '10.0 / 3', 10.0 / 3
UNION ALL
SELECT '10 / 3.0' , 10 / 3.0
UNION ALL
SELECT 'CAST(10 AS numeric) / 3 ' , CAST(10 AS numeric) / 3
UNION ALL
SELECT '(CAST(1 AS numeric) * 10) / 3' , (CAST(1 AS numeric) * 10) / 3
UNION ALL
SELECT '(1.0 * 10) / 3' , (1.0 * 10) / 3
UNION ALL
SELECT '10 / (3 * 1.0 )' , 10 / (3 * 1.0 )
) AS T
沒有留言:
張貼留言