原貼: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 行)
--所有的值都是隨機取的.........