come ,看这简音的SQL怎么写!!
X表如下:
A B
1 5
6 10
9 18
-1 20
要求用一条SQL查询出如下结果:
A B C
1 1 1
6 6 7
9 18 25
-1 20 45
即描述如下:
1,当A 的值> 1 且 <6时,B列显示A的值,否则不变;
2,C列的值是B列逐行累加的值
------解决方案--------------------declare @t table(id int identity(1,1),A int, B int)
insert @t
select 1, 5 union all
select 6, 10 union all
select 9, 18 union all
select -1, 20
SELECT A,
B = case when A between 1 and 6 then A else B end,
C = (select sum(case when A between 1 and 6 then A else B end) from @t where id <= a.id)
FROM @t as a
/*结果:
A B C
-------------------------------
1 1 1
6 6 7
9 18 25
-1 20 45
*/
------解决方案--------------------解决了
------解决方案--------------------有我的分吗?
------解决方案--------------------方便的话给sdhylj吧,马甲.
------解决方案--------------------hellowork(一两清风)偷偷加了格自增列。 :)
------解决方案--------------------我的是借用了臨時表
Create Table X
(A Int,
B Int)
Insert X Select 1, 5
Union All Select 6, 10
Union All Select 9, 18
Union All Select -1, 20
GO
Select ID = Identity(Int, 1, 1), A, (Case When A > = 1 And A <= 6 Then A Else B End) As B Into #T From X
Select A, B, (Select SUM(B) From #T Where ID <= A.ID) As C From #T A
Drop Table #T
GO
Drop Table X
--Result
/*
A B C
1 1 1
6 6 7
9 18 25
-1 20 45
*/
------解决方案--------------------select A,case when A> 1 and A < 6 then A else B end as B,(select sum(case when A> 1 and A < 6 then A else B end ) from temp as D where temp.id > D.id) as c from temp
------解决方案--------------------没办法,算是略施小计吧,不知能不能骗过楼主:)
------解决方案--------------------1,当A 的值> 1 且 <6时,B列显示A的值,否则不变;
------------------
樓主的這個描述有問題,應該是
1,当A 的值> =1 且 <=6时,B列显示A的值,否则不变;