日期:2014-05-18  浏览次数:20467 次

求一汇总语句
表格如下:    
kid     mid               tid     sss     qqq    
1             2               2           1             0    
1             2             33           1             0    
1             2             141         0             1    
1             2             166         1             0        
1             2             733         0             1    
 
sss/qqq不同时为1或者0.    
希望得到如下结果    
 
 
kid     mid               tid     sss     qqq    
1             2               2           1             0    
1             2             33           2             0    
1             2             141         2             1    
1             2             166         3             1        
1             2             733         3             2      


------解决方案--------------------
declare @a table(kid int, mid int, tid int, sss int ,qqq int)
insert @a select 1 ,2 ,2 ,1 ,0
union all select 1 ,2 ,33 ,1, 0
union all select 1, 2, 141, 0, 1
union all select 1, 2, 166, 1, 0
union all select 1, 2, 733, 0, 1

select kid,mid,tid,sss=(select sum(sss) from @a where kid=a.kid and mid=a.mid and tid <=a.tid),
qqq=(select sum(qqq) from @a where kid=a.kid and mid=a.mid and tid <=a.tid)
from @a a
------解决方案--------------------
看看理解的是否正確

Create Table TEST
(kid Int,
mid Int,
tid Int,
sss Int,
qqq Int)
Insert TEST Select 1, 2, 2, 1, 0
Union All Select 1, 2, 33, 1, 0
Union All Select 1, 2, 141, 0, 1
Union All Select 1, 2, 166, 1, 0
Union All Select 1, 2, 733, 0, 1
GO
--查詢
Select
kid,
mid,
tid,
(Select Count(*) From TEST Where sss = 1 And tid <= A.tid) As sss,
(Select Count(*) From TEST Where qqq = 1 And tid <= A.tid) As qqq
From
TEST A


--更新
Update
A
Set
sss = (Sele