日期:2014-05-17  浏览次数:20911 次

用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]

------解决方案--------------------
select trueName, min(userName),sum(score)
from tb
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
/*
trueName username score
张三          zs2         270
*/

------解决方案--------------------
select truename,max(username)username,SUM(score)
from [huang]
GROUP BY truename
order by checksum(newid())
------解决方案--------------------
联机丛书上的原话:MAX can be used with numeric, character, uniqueidentifier, and datetime columns, but not with bit columns