SQL Server2000聚合函數(shù)和空值
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
SQL Server2000的聚合函數(shù)大都會(huì)忽略空值,所以在含有空值的列上使用聚合函數(shù)時(shí)需格外謹(jǐn)慎。例如有一個(gè)Student表如下:
![]() 我們用下邊SQL語句統(tǒng)計(jì)下人數(shù)、平均年齡、最大年齡、最小年齡: 程序代碼 select count(*) as count1, count(age) as count2, avg(age) as [avg], max(age) as [max], min(age) as [min] from Student 引用內(nèi)容 count1 count2 avg max min ----------- ----------- ----------- ----------- ----------- 3 2 21 22 20 可以看到,除了count(*),其他聚合函數(shù)都忽略了stu3。可以使用isnull函數(shù)給空值設(shè)置一個(gè)默認(rèn)值,讓聚合函數(shù)不忽略該行: 程序代碼 select count(*) as count1, count(isnull(age,0)) as count2, avg(age) as [avg], max(age) as [max], min(age) as [min] from Student 引用內(nèi)容 count1 count2 avg max min ----------- ----------- ----------- ----------- ----------- 3 3 21 22 20 注意:對avg、max、min聚合函數(shù)不應(yīng)使用isnull,否則會(huì)出現(xiàn)用兩個(gè)人的年齡計(jì)算三個(gè)人的平均年齡,這顯然是不合理的。 很多時(shí)候,我們都會(huì)給字段設(shè)置一個(gè)默認(rèn)值,當(dāng)字段值為空值時(shí)就使用默認(rèn)值,再看Student表: ![]() 我們用下邊SQL語句統(tǒng)計(jì)下人數(shù)、平均年齡、最大年齡、最小年齡: 程序代碼 select count(*) as count1, count(age) as count2, avg(age) as [avg], max(age) as [max], min(age) as [min] from Student 引用內(nèi)容 count1 count2 avg max min ----------- ----------- ----------- ----------- ----------- 3 3 14 22 0 很顯然,avg、min的值不是我們想要的,avg和min都應(yīng)忽略stu3,這時(shí)我們可以用nullif函數(shù)讓聚合函數(shù)忽略它: 程序代碼 select count(*) as count1, count(nullif(age,0)) as count2, avg(nullif(age,0)) as [avg], max(nullif(age,0)) as [max], min(nullif(age,0)) as [min] from Student 引用內(nèi)容 count1 count2 avg max min ----------- ----------- ----------- ----------- ----------- 3 2 21 22 20 說明:當(dāng)以文本顯示查詢時(shí),若對含空值的列使用聚合函數(shù),SQL查詢分析器會(huì)發(fā)出警告。 引用內(nèi)容 count1 count2 avg max min ----------- ----------- ----------- ----------- ----------- 3 2 21 22 20 (所影響的行數(shù)為 1 行) 警告: 聚合或其它 SET 操作消除了空值。 該文章在 2011/3/13 0:27:51 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |