用group by 分组,没有分组的字段随便取一条记录
例如:
id trueName userName score
1 张三 zs 80
2 张三 zs1 100
3 张三 zs2 90
想要获得张三的总分(userName 随便去一个值即可):
张三 zs 270 或 张三 zs1 270 或 张三 zs1 270
group?by问题
[解决办法]
create table #t([id] int,[trueName] varchar(4),[userName] varchar(3),[score] int)
insert #t
select 1,'张三','zs',80 union all
select 2,'张三','zs1',100 union all
select 3,'张三','zs2',90
go
select [trueName],MAX([userName]),SUM([score])
FROM #t
GROUP BY [trueName]
if object_id('tb') is not null drop table tb
go
create table tb([id] int,[trueName] varchar(4),[userName] varchar(3),[score] int)
insert tb
select 1,'张三','zs',80 union all
select 2,'张三','zs1',100 union all
select 3,'张三','zs2',90
select trueName,max(username) as username,sum(score) as score
from tb
GROUP BY truename
/*
trueNameusernamescore
张三 zs2 270
*/