在SQL中选择具有相同ID的另一行时字段的总和

时间:2014-04-25 17:55:18

标签: mysql sql

我有两张桌子

CREATE TABLE users
(
  id int
);

CREATE TABLE attributes
(
  user_id int,
  k char(100),
  v char(100)
);

insert into users values (1);
insert into users values (2);
insert into users values (3);

insert into attributes values (1, 'k1', 'v1');
insert into attributes values (1, 'k2', 2);
insert into attributes values (2, 'k1', 'v1');
insert into attributes values (2, 'k2', 7);
insert into attributes values (3, 'k1', 'v2');
insert into attributes values (3, 'k2', 11);

我想要的是

  • 对于属性表中的每个不同v1,请将同一user_id下的另一行的值相加并k=k2

所以我想要像

这样的结果
 v1 9
 v2 11

当前SQL:

SELECT v, '?' as total 
FROM users 
JOIN attributes ON users.id = attributes.user_id 
WHERE k = 'k1' 
GROUP BY v

http://sqlfiddle.com/#!2/36920/3/0

2 个答案:

答案 0 :(得分:2)

这正是您所需要的。我完全赞同aardvarkk,最后更明智的选择可能只是简化你的架构。不管怎么说..

SELECT a1.v, SUM(a2.v) FROM users u
INNER JOIN attributes a1 ON a1.user_id = u.id
INNER JOIN attributes a2 ON a2.user_id = a1.user_id AND a2.k = 'k2'
WHERE a1.k = 'k1'
GROUP BY a1.v

答案 1 :(得分:0)

create table sumv
(
vnmbr nchar(2),
v int
)
declare @nmbr nvarchar
set @nmbr = 1
while @nmbr < 3
begin
insert into sumv (vnmbr,v)
select 'v'+@nmbr,v from attributes where [user_id] in (select [user_id] from attributes
where v = 'v'+@nmbr) and v not like 'v%'
set @nmbr = @nmbr + 1
end
select vnmbr,sum(v) as [sumv] from sumv group by vnmbr