關於SQL語句Count的一點細節

2021-05-05 21:34:06 字數 1054 閱讀 2114

count語句支援*、列名、常量、變數,並且可以用distinct關鍵字修飾, 並且count(列名)不會累計null的記錄。下面隨便用一些例子示範一下count的規則:比如對如下表做統計,所有列這裡都用sql_variant型別來表示。

if (object_id ('t_test' )> 0 )

drop table t_test

go create table t_test (a sql_variant , b sql_variant , c sql_variant )

insert into t_test select 1 , 1 , 'a'

insert into t_test select 1 , getdate (), null

insert into t_test select 'a' , null , 1

insert into t_test select 3 , null , null

insert into t_test select null , null , null

go select * from t_test

go select

count (* )                --總數

, count (nullif (1 , 1 ))        --永遠返回0

, count (a )                --a數量

, count (b)                --b數量

, count (distinct a )        --a不重複數量

, count (isnull (b, c ))        --b或者c不為null數量

, count (coalesce (a , b, c ))    --a或者b或者c不為null數量

, count (nullif (a , b))        --a不等於b的數量

, count (nullif (isnumeric (cast (a as varchar (38 ))), 0 ))--a是數字的數量

from t_test

關於SQL語句Count的一點細節

count語句支援 列名 常量 變數,並且可以用distinct關鍵字修飾,並且count 列名 不會累計null的記錄。下面隨便用一些例子示範一下count的規則 比如對如下表做統計,所有列這裡都用sql variant型別來表示。if object id t test 0 drop table ...

關於SQL語句Count的一點細節

count語句支援 列名 常量 變數,並且可以用distinct關鍵字修飾,並且count 列名 不會累計null的記錄。下面隨便用一些例子示範一下count的規則 比如對如下表做統計,所有列這裡都用sql variant型別來表示。if object id t test 0 drop table ...

關於SQL語句Count的一點細節

count語句支援 列名 常量 變數,並且可以用distinct關鍵字修飾,並且count 列名 不會累計null的記錄。下面隨便用一些例子示範一下count的規則 比如對如下表做統計,所有列這裡都用sql variant型別來表示。if object id t test 0 droptablet ...