[英]SQL : How to sum a column based on the range of value in another column in SQL?
[英]SQL SUM() by value of another column
我在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
我可以通過搜索個人用戶ID +以0001結尾的ValueKey來輕松找到個人的分數。我還可以通過搜索其用戶ID + ValueKey以0002結尾的行的值來查找個人所在的團隊。
我的問題是,如何獲得球隊得分列表? 在這種情況下,團隊1將擁有70,而團隊2將擁有35。
這是一種方法:
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
);
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
--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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.