优秀的编程知识分享平台

网站首页 > 技术文章 正文

SQL语句distinct的多列问题(数据库distinct多列)

nanyue 2024-10-20 07:42:28 技术文章 5 ℃

distinct 多列问题结合group by的解决方法

表 table1

id RegName PostionSN PersonSN

1 山东齐鲁制药 223 2

2 山东齐鲁制药 224 2

3 北京城建公司 225 2

4 科技公司 225 2

我想获得结果是

id RegName PostionSN PersonSN

1 山东齐鲁制药 223 2

3 北京城建公司 225 2

4 科技公司 225 2

select distinct RegName,PostionSN,PersonSN from table1;

如果查询的是多列 distinct 用和不用一样

只能用group by

用group by RegName

select * from table1 where id in (select min(id) from table1 group by RegName) and PersonSN=2;

SQLSever中distinct的用法(不重复的录)

下面先来看看例子:

table表

字段1 字段2

id name

1 a

2 b

3 c

4 c

5 b

库结构大概这样,这只是一个简单的例子,实际情况会复杂得多。

比如我想用一条语句查询得到name不重复的所有数据,那就必须

使用distinct去掉多余的重复记录。

select distinct name from table;

得到的结果是:

----------

name

a

c

好像达到效果了,可是,我想要得到的是id值呢?改一下查询语句吧:

select distinct name, id from table;

结果会是:

----------

id name

1 a

2 b

3 c

4 c

5 b

distinct怎么没起作用?作用是起了的,不过他同时作用了两个

字段,也就是必须得id与name都相同的才会被排除

我们再改改查询语句:

select id, distinct name from table

很遗憾,除了错误信息你什么也得不到,distinct必须放在开头。难到不能把distinct放到where条件里?能,照样报错。

下面方法可行:

select *, count(distinct name) from table group by name;

结果:

id name count(distinct name)

1 a 1

2 b 1

3 c 1

最后一项是多余的,不用管就行了,目的达到

group by 必须放在 order by 和 limit之前,不然会报错

1 山东齐鲁制药 223 2

2 山东齐鲁制药 224 2

3 北京城建公司 225 2

4 科技公司 225 2

我想获得结果是

id RegName PostionSN PersonSN

1 山东齐鲁制药 223 2

3 北京城建公司 225 2

4 科技公司 225 2

select distinct RegName,PostionSN,PersonSN from table1;

如果查询的是多列 distinct 用和不用一样

只能用group by

用group by RegName

select * from table1 where id in (select min(id) from table1 group by RegName) and PersonSN=2;

最近发表
标签列表