怎样对多个字段去重并计数?

来源:互联网 发布:linux grub引导 stage 编辑:程序博客网 时间:2024/04/30 15:49

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语句。


参考:http://www.cnblogs.com/xiepeixing/archive/2012/04/18/2583955.html

0 0