这个语句如何写
t1的数据如下:
f1 f2 f3
A 销售 10
A 进仓 30
A 进仓 40
A 出仓 15
B 进仓 70
B 销售 10
B 销售 20
B 出仓 10
我想实现以下的数据:
f1 进仓 销售 出仓 结存
A 70 10 15 45
B 70 30 10 30
结存=进仓-销售-出仓,如果用游标如何实现?但最好不要用游标实现,有没有其它的SQL语句来实现呢?
问题点数:50、回复次数:4Top
1 楼pengda1i(冒牌大力 V0.4)回复于 2005-06-14 10:17:18 得分 25
select f1,
sum(case f2 when '进仓' then f3 else 0 end) as 进仓,
sum(case f2 when '销售' then f3 else 0 end) as 销售,
sum(case f2 when '出仓' then f3 else 0 end) as 出仓,
sum(case f2 when '进仓' then f3 when '销售' then -f3 when '出仓' then -f3 else 0 end) as 结存
from t1
group by f1
Top
2 楼Frewin(frewin)回复于 2005-06-14 10:18:39 得分 0
Select A.F1 ,B.进仓,C.销售,D.出仓,(Isnull(B.进仓,0)-Isnull(C.销售,0)-Isnull(D.出仓,0)) As 结存
From T1 a LEFT Join (Select f1,Sum(f3) as 进仓 from t1 where f2='进仓' Group By f1) B
On a.f1 = b.f1
Left Join (Select f1,Sum(f3) as 销售 from t1 where f2='销售' Group By f1) c
On a.f1 = c.f1
Left Join (Select f1,Sum(f3) as 出仓 from t1 where f2='出仓' Group By f1) d
On a.f1 = d.f1Top
3 楼libin_ftsafe(子陌红尘:TS for Banking Card)回复于 2005-06-14 10:20:20 得分 25
select
f1,
进仓 = sum(case f2 when '进仓' then f3 else 0 end),
销售 = sum(case f2 when '销售' then f3 else 0 end),
出仓 = sum(case f2 when '出仓' then f3 else 0 end),
结存 = sum(case f2 when '进仓' then f3 else -1*f3 end)
from
t1
group by
f1
order by
f1
Top
4 楼wangdehao(找找找(现在很幸福))回复于 2005-06-14 10:21:48 得分 0
select f1,进仓=sum(case when f2='进仓'then f3 else 0 end),销售=sum(case when f2='销售'then f3 else 0 end),出仓=sum(case when f2='出仓'then f3 else 0 end),结存=(进仓-销售-出仓)group by f1Top




