distinct 和 group by 两种方法
distinct:
select distinct name from t1 能消除重复记录,但只能取一个字段,现在要同时取id,name这2个字段的值。
select distinct id,name from t1 可以取多个字段,但只能消除这2个字段值全部相同的记录
group by
所以用distinct达不到想要的效果,用group by 可以解决这个问题。
例如要显示的字段为A、B、C三个,而A字段的内容不能重复可以用下面的语句:
select A, min(B),min(C),count(*) from [table] where [条件] group by A
having [条件] order by A desc
本文介绍了在SQL中使用distinct和group by进行数据去重的方法。distinct适用于去除单个字段的重复值,而当需要考虑多个字段时,group by则更为有效。通过实例展示了如何结合聚合函数实现更复杂的查询需求。
3800

被折叠的 条评论
为什么被折叠?



