Home> php教程> php手册> body text

一个有关DISTINCT的问题解答

WBOY
Release: 2016-06-13 10:05:23
Original
1028 people have browsed it

经常会有朋友问到类似于这样的问题,
表中的数据如下
ID AA BB
1 123 456
1 4535 54
1 60 6564
1 60 656
2 50 664
2 60 6
3 89 89
4 40 4242
希望得到的结果是
ID AA BB
1 123 456
2 50 664
3 89 89
4 40 4242
当然了,环境是SQL Server
解答及分析如下:
1, 不少朋友希望用distinct就解决问题,但不可能,disctinct将重复的记录忽略,
但它忽略的是完全一致的重复记录,而不是其中某个字段重复的记录,所以也只有
这样的语法
select distinct ID,AA,BB from tName
其它诸如select distinct(ID),AA,BB from tName 或
select ID,distinct AA,BB的写法都是无效的
2, 使用group by和聚合函数
select ID,MAX(AA) AS AA,MAX(BB) AS BB from tName group by ID
可以得到如下结果
ID AA BB
1 4535 6564
2 60 664
3 89 89
4 40 4242
ID是唯一了,但不一定后面的字段是同一条记录的
3, 使用临时表
select IDENTITY(INT,1,1) as TID,ID,AA,BB into #Tmp from tName
select t1.ID,t1.AA,t1.BB from #Tmp t1 where t1.TID in
(select min(T2.TID) from #Tmp t2 group by t2.ID)
这样可以得到符合要求的结果
不过用了两个T-SQL语句,
而且如果是大数据量的话,性能问题将很突出
到目前为止,我还没找到用一个T-SQL语句实现同样功能的方法,
如果谁有,希望补充

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!