sql语句请高手帮忙!
表AA
id user_id class_id shu
1 100 2 50
2 200 4 5
3 100 3 10
4 100 2 20
5 100 2 20
6 100 3 20
结果:
id user_id class_id shu
1 100 2 90
2 100 3 30
------解决方案--------------------2 200 4 5这条记录不计入结果地原因是???
------解决方案-------------------- Select
[user_id],
class_id,
SUM(shu) As shu
From
AA
Where [user_id] = 100
Group By [user_id], class_id
------解决方案--------------------如果要生成前面的ID列的話,就要借助臨時表了。
------解决方案--------------------declare @t table(id int,[user_id] int,class_id int,shu int)
insert @t select 1, 100, 2, 50
union all select 2, 200, 4, 5
union all select 3, 100, 3, 10
union all select 4, 100, 2, 20
union all select 5, 100, 2, 20
union all select 6, 100, 3, 20
--方法1
select identity(int,1,1) as id,[user_id],class_id,sum(shu) as shu into #t from @t where [user_id]=100 group by [user_id],class_id
select * from #t
drop table #t
--方法2
select (select count(distinct class_id)+1 from @t where class_id <a.class_id and [user_id]=100) as id,
[user_id],class_id,sum(shu) as shu
from @t a where [user_id]=100 group by [user_id],class_id
------解决方案--------------------结果忘了贴
(所影响的行数为 6 行)
(所影响的行数为 2 行)
id user_id class_id shu
----------- ----------- ----------- -----------
1 100 2 90
2 100 3 30
(所影响的行数为 2 行)
id user_id class_id shu
----------- ----------- ----------- -----------
1 100 2 90
2 100 3 30
(所影响的行数为 2 行)
------解决方案--------------------与BB关联的依据是什么????如果是AA.id=BB.ID的话,问什么class_id=2对应的是id=1的BB记录,为什么不是4的?