SQL Sum和Group通过更改组的值

时间:2017-02-23 16:00:57

标签: sql group-by sum

如果有多个

,我如何对值进行分组并更改其中一个值
Table
ID | VALUE | NAME
1  |   2   | John
1  |   5   | Carl
2  |   4   | Elis
2  |   1   | Ted
3  |   2   | James


RESULT

ID | VALUE | NAME
1  |   7   |  *
2  |   5   |  *
3  |   2   | James

2 个答案:

答案 0 :(得分:2)

以下是一种适用于任何数据库的方法:

select id, sum(value) as value,
       (case when min(name) = max(name) then min(name) else '*' end) as name
from t
group by id;

答案 1 :(得分:0)

这是您必须尝试的其他查询

Select ID, sum(Value) Value, NAME = ( Select b.Name + ' ' AS [text()]
            From dbo.test b
            Where a.ID = b.ID
            ORDER BY a.ID
            For XML PATH (''))
from test a
group by ID
order by ID