t sql中的COUNT函式

2022-02-18 06:13:42 字數 2848 閱讀 1056

1 count函式的定義

count函式的定義可見msdn。定義如下:

count (  )
那麼count 有兩種使用方式count(expression)和count(*),它返回乙個對乙個表按某列計數的值。
以此可以得出乙個結論:count(*)返回值總是大於或等於count(expression)的返回值。
在應用中,好多人喜歡使用count(1),這裡面的1其實就是乙個expression,因為你的表中沒有列名為1的列,那麼它的返回結果是和count(*)一模一樣的,
個人覺得效率也是沒有差別的。
;with cte1(c1,c2, description) as(

select 1, 1, 'this is a fox' union all

select 2, null, 'firefox' union all

select null, 2, 'people consider foxes as clever but sly animals' union all

select null, null, null union all

select 3, null, 'this is me' union all

select 3, 3, 'fox on the run')

結果如下:

如結果所示,count(*),count(2)和count(3)是一模一樣的。而count(c1)顯然過濾掉了null值。

注意,count 的引數expression可以為常量(像上面的2,3…),表的列,函式,還可以是語句,具體可見msdn的定義。下面展示了這個應用。

如果想為cte1中列description中有字串'fox』進行計數,典型的做法是:

select count(*) from cte1

where patindex('%fox%',cte1.description) <> 0

這種做法是where中過濾,另外一種方式是在expression中定義查詢條件:

select count(nullif(patindex('%fox%', cte1.description), 0))

from cte1

如果description列中沒有字串'fox'那麼patindex函式返回的是0,nullif函式因為兩個引數相等,那麼結果是null,因為null不會參與計數,所以列中沒有'fox』的行不會

參與計數,達到了查詢的目的。

當然,我們還可在expression中使用case表示式:

select count(case 

when patindex('%fox%',cte1.description) <> 0 then 1

elsenullend)

from cte1

注意else語句後面必須是null,如果是非null,else語句也會參與count計數的。

2 在count函式後接聚合視窗函式over。注意聚合視窗函式中是不能有order by,order by只能出現在排名函式的over子句中。over字句的定義見msdn。

select c.*, count(*) over(partition by c.c1) 'c1 * count',

count(c1) over(partition by c.c1) 'c1 c1 count',

count(*) over(partition by c.c2) 'c2 count',

count(case

when left(c.description, 1) in ('t') then 1

else null end) over(partition by left(c.description, 1)) 'start with t',

count(case

when left(c.description, 1) in ('t', 'f', 'p') then 1

else null end) over(partition by left(c.description, 1)) 'start with t, f or p'

from cte1 c

注意over字句不能為over(partition by c.c1 order by c.c1),這是因為count不是排名函式。
以上的執行結果為:

可以看出,在使用over子句時候,count還是遵循了最基本的準則,count(*)會對null行計數,而count(expression)則不會。

以上在count 的expression中設定條件顯然不是一種很優化的方式,因為這種方式會首先讀取表中的所有資料,是對錶進行掃瞄,而在where子句中設定條件進行過濾是一種很好的方式。因為從邏輯上講,where先於select執行,所有資料庫引擎只會讀取部分資料,不是讀取所有資料。如果要對以表中c1列的null進行統計,可以有兩種方式:

select count(*)

from cte1

where c1 is null

或者:

select count(case

when c1 is null then 'x'

else null end)

from cte1

最後看看執行計畫的比較,後面的方式多了乙個步驟(過濾):

t sql中的COUNT函式

t sql中的count函式 count函式的定義可見msdn。定義如下 count 那麼count 有兩種使用方式count expression 和count 它返回乙個對乙個表按某列計數的值。1.count 返回表的行數。它不會過濾null和重複的行。2.count expression 會過...

MySql中的count 函式

1.count 函式是用來統計表中記錄的乙個函式,返回匹配條件的行數。2.count 語法 1 count 包括所有列,返回表中的記錄數,相當於統計表的行數,在統計結果的時候,不會忽略列值為null的記錄。2 count 1 忽略所有列,1表示乙個固定值,也可以用count 2 count 3 代替...

MySql中的count函式

1.count 函式是用來統計表中記錄的乙個函式,返回匹配條件的行數。2.count 語法 1 count 包括所有列,返回表中的記錄數,相當於統計表的行數,在統計結果的時候,不會忽略列值為null的記錄。2 count 1 忽略所有列,1表示乙個固定值,也可以用count 2 count 3 代替...