/*
對於null,
即是可以查詢到記錄的,null不能做常見運算,如相加、相乘、判斷是否相等。
在計算時,要isnull(字段名,0)或isnull(字段名,'其他')再做計算。 */
-- 錯誤的:
-- 沒有統計進bd_code為null的
select
temp00.name0,
temp01.num0
from
temp00
left join
temp01
on
temp00.bd_code=temp01.bd_code
-- 正確定:
-- 將bd_code為為null的歸為一類
select
temp00.name0,
temp01.num0
from
temp00
left join
temp01
on
isnull(temp00.bd_code,'')=isnull(temp01.bd_code,'')
/*
對於0
常見錯誤為,0作為分母。 */
-- 錯誤的:
with
temp00 as(
select
sum(實收) num0
from
實收表),
temp01 as(
select
sum(應收) num1
from
應收表)
select
temp00.實收/temp01.應收 actu_num
from
temp00
left join
temp01
on 1=1
-- 正確的:
with
temp00 as(
select
sum(實收) num0
from
實收表),
temp01 as(
select
sum(應收) num1
from
應收表)
select
case
when temp01.應收=0
then 0
else
temp00.實收/temp01.應收
end actu_num
from
temp00
left join
temp01
on 1=1
/*
對於空查詢,
也就是沒有查詢記錄,即使你用isnull轉換也沒用,他沒有查詢記錄。
沒有查詢記錄再進行計算,當然是null的。 */
-- 錯誤的
with
temp00 as(
select
sum(基本工資) num0
from
工資表),
temp01 as(
select
sum(加班工資) num1
from
加班表)
select
temp00.num0+temp01.num1 actu_num
from
temp00
left join
temp01
on 1=1
-- 正確的
with
temp00 as(
select
sum(基本工資) num0
from
工資表
union all
select 0 num0),
temp01 as(
select
sum(加班工資) num1
from
加班表
union all
select 0 num1)
select
sum(temp00.num0)+sum(temp01.num1) actu_num
from
temp00
left join
temp01
on 1=1