美文网首页
distinct使用笔记!

distinct使用笔记!

作者: DragonersLi | 来源:发表于2021-02-19 14:05 被阅读0次

一条sql语句统计某月去重申请产品记录

需求:导出X月份所有产品申请记录,同一手机号去重
#无去重写法
select productId,p.productName,count(aid) record 
from pjh_action_record r left join pjh_productinfo p on r.productId = p.id
where  r.createTime BETWEEN 1609430400 and 1612108800
group by productId order by record desc
统计记录无去重
#去重子查询作为字段返回
select productId,p.productName,count(aid) record,(
select count(distinct mobile) uniq_record from pjh_action_record 
where productId = r.productId and createTime BETWEEN 1609430400 and 1612108800
) uniq_record
from pjh_action_record r left join pjh_productinfo p on r.productId = p.id
where  r.createTime BETWEEN 1609430400 and 1612108800
group by productId order by record desc

去重子查询作为字段返回

(select count(distinct mobile) uniq_record1 from pjh_action_record 
where productId = r.productId and createTime BETWEEN 1609430400 and 1612108800) uniq_record

1.子查询必须为单一字段,如果多个字段则报错:1241 - Operand should contain 1 column(s)
2.子查询内部字段别名会被外面的别名覆盖:uniq_record会覆盖uniq_record1 
3.去重常用的方法:groupby分组,distinct去重
4.distinct去重使用:
①如果多个字段查询,distinct 字段必须写在最前,否则会报语法错误; select id,distinct mobile ...
②如果是统计去重字段的总数: count(distinct 字段) 则不用放在最前;select id,count(distinct mobile) ...
③如果distinct后跟多个字段,则去重条件是这多个字段的组合有重复。select  distinct mobile m,name n ...
去重子查询作为字段返回

mysql带条件查询多个count实现
用第一种方式会展示多行结果,第二种只会展示一行结果,方便对结果做运算!

用group by分组统计

select id,status,count( DISTINCT id) total from table group by status

id  status total
6000004 1  146244
6000044 2  112036
6000001 3   508

使用count(distinct if(field=x,主键ID,null))方式统计

select id,status,count(DISTINCT if(status=1,id,null)) aa,
count(DISTINCT if(status=2,id,null)) bb,
count(DISTINCT if(status=3,id,null)) cc 
table

aa     bb   cc
171347  63206   410770

相关文章

  • distinct使用笔记!

    需求:导出X月份所有产品申请记录,同一手机号去重 去重子查询作为字段返回

  • 《SQL权威指南读书笔记》第三章

    1、使用as使用别名,例如: 2、使用distinct来去除列中的重复元素,例如: 但是应尽量减少distinct...

  • Django ORM去重

    distinct()具有去重功能是没有必要怀疑的,distinct()函数有一个隐藏特性,当使用distinct(...

  • ContentProvider使用Distinct

    在使用ContentProvider做数据库数据查询时,默认是不处理重复数据的,如果你需要过滤重复数据,可以采用D...

  • mysql 使用上的问题

    DISTINCT关键字 不能部分使用DISTINCT DISTINCT关键字应用于所有列而不仅是前置它的列。如果给...

  • SQLite Distinct 关键字

    SQLite Distinct 关键字 SQLite 的 DISTINCT 关键字与 SELECT 语句一起使用,...

  • mysql distinct去重

    在使用distinct时发现,select distinct name from t1;会去掉重复的id记录。但是...

  • 01-mysql基础

    1 null值注意 count数据丢失null值行 distinct数据丢失当使用count(distinct c...

  • 提高MYSQL查询效率

    1、能使用(NOT)EXISTS替代(NOT)IN的地方,尽量使用EXISTS;使用EXISTS替代DISTINCT。

  • distinct仅列出不同的列值

    如果想统计查看一个列有哪些值(去掉重复的),只需使用distinct关键字,如下: SELECT DISTINCT...

网友评论

      本文标题:distinct使用笔记!

      本文链接:https://www.haomeiwen.com/subject/kckyextx.html