当前位置:数据库 > SQLServer >>

统计数据的时候,经常遇到重复问题,解决方案!

答案:
原贴:http://community.csdn.net/Expert/topic/3717/3717577.xml?temp=.4141199

有这样的一张表(有三列a、b、c):
a      b      c 
1     two    2003
1     two    2005
1     two    2004
2     four   2006
3     four   2008
现在我想把a、b列有相同值的记录合成一条记录,结果集如下:
a      b      c 
1     two    2004(该值也可以取2003或2005)
2     four   2006
3     four   2008
这样的sql语句怎么写??


--测试:

create table 表(a varchar(20), b varchar(20), c varchar(20) )
insert 表 select '1',    'two',   '2003'
union all select '1',    'two',   '2005'
union all select '1',    'two',   '2004'
union all select '2',    'four',  '2006'
union all select '3',    'four',  '2008'
go

select a,b
,(select top 1 c from 表 where a = d.a and b = d.b order by newid()) as c    
                                                                            --随机取c列的值,也可以用Max(c),Min(c), AVG(c)
from 表 d
group by a,b  --a,b 组合分组


drop table 表


--第一次测试结果:
a                    b                    c                   
-------------------- -------------------- --------------------
1                    two                  2004
2                    four                 2006
3                    four                 2008

(所影响的行数为 3 行)

--第二次测试结果:

a                    b                    c                   
-------------------- -------------------- --------------------
1                    two                  2005
2                    four                 2006
3                    four                 2008

--第十次测试结果:

a                    b                    c                   
-------------------- -------------------- --------------------
1                    two                  2003
2                    four                 2006
3                    four                 2008

(所影响的行数为 3 行)


--所有的值都是随机取的.........

上一个:SQL Server 中 自定义函数 和 游标 应用的经典案例
下一个:使用SQL Server发送邮件

Oracle
MySQL
Access
SQLServer
DB2
Excel
SQLite
SYBASE
Postgres
如果你遇到数据库难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,