SQL SUM()按另一列的值

时间:2016-10-20 10:52:56

标签: sql sql-server

我正在MS SQL Server中创建通用键/值数据存储。我有一个UserDecimalData表定义如下

create table [UserDecimalData] (
    [UserID] nvarchar(64) not null,
    [ValueKey] uniqueidentifier not null,
    [Value] decimal null
);
alter table [UserDecimalData]
    add constraint PK_UserDecimalData primary key clustered ([UserID], [Date], [ValueKey]);

并且作为示例,这里是一些数据,其使用以0001结尾的GUID来指示游戏中的个人得分,以及以0002结尾的GUID以指示用户在哪个团队。

UserID  ValueKey                                Value
Dave    00000000-0000-0000-0000-000000000001    35
Dave    00000000-0000-0000-0000-000000000002    1
Phil    00000000-0000-0000-0000-000000000001    35
Phil    00000000-0000-0000-0000-000000000002    1
Pete    00000000-0000-0000-0000-000000000001    35
Pete    00000000-0000-0000-0000-000000000002    2

我可以通过搜索以0001结尾的UserID + ValueKey轻松找到个人的分数。我还可以通过搜索他们的UserID + ValueKey结束的行的值来找出个人所在的团队。 0002。

我的问题是,如何获得团队成绩列表?在这种情况下,团队1将拥有70,团队2将拥有35。

4 个答案:

答案 0 :(得分:2)

这是一种方法:

select sum(udd.value)
from UserDecimalData udd
where udd.ValueKey like '%1' and
      exists (select 1
              from UserDecimalData udd2
              where udd2.ValueKey like '%2' and
                    udd2.UserId = udd.UserId
             );

答案 1 :(得分:1)

select v1.Value as Team, sum(v2.value) as TeamScore 
from userdecimaldata v1
join userdecimaldata v2 on v2.UserId = v1.UserId and v2.[Date] = v1.[Date]
where v1.ValueKey = @clankey and v2.ValueKey = @scoreKey
group by v1.Value

输出

 Team   TeamSccore
    1   70
    2   35

答案 2 :(得分:0)

--first way
with commands as (
    select UserID as UserID, Value as command
    from UserDecimalData
    where ValueKey like '%2'
)
select c.command, sum(Value)
from UserDecimalData u
    left join commands c on u.UserID = c.UserID
where ValueKey like '%1'
group by command
GO

--second way
select c.command, sum(Value)
from UserDecimalData u
    left join (
            select UserID as UserID, Value as command
            from UserDecimalData
            where ValueKey like '%2'
        ) c on u.UserID = c.UserID
where ValueKey like '%1'
group by command
GO

--results
--1 70
--2 35

答案 3 :(得分:0)

select u1.Value, sum(u0.Value)
from UserDecimalData u1
    left join UserDecimalData u0 on u0.UserID = u1.UserID and u0.ValueKey like '%1' 
where u1.ValueKey like '%2'
group by u1.Value 

GO