1. 程式人生 > >怎樣對多個欄位去重並計數?

怎樣對多個欄位去重並計數?

Distinct可以和Count 一起使用,去重並計數:

COUNT({ DISTINCT expression})

但是一起使用時,後面不能有多個欄位:

  1. //不允許的寫法:
  2. select count(distinct col1 , col2 , col3 ,.......)from table

變通的方法:

一、將去重程式碼放在後面。

  1. select count(*)from(select distinct col1 ,col2 , col3 from table A)

二、把多個欄位連成一個欄位。

相當於把多個欄位的字串連線起來: 

  1. select count(DISTINCT fcode
    +cast(fread_date as varchar(30)))from my_table

第二種方法雖然效率不高,但可以簡化SQL語句。