求个SQL查询语句,谢谢
BK_NO etd_pol amount IC
001 2007/01/08 100 I
001 2007/01/08 200 I
001 2007/01/08 150 C
002 2007/01/08 200 I
002 2007/01/08 150 I
002 2007/01/08 150 C
IC字段中的I代表:收入,C代表:支出
算每个以BK_NO分组的总收入,总支出,以及利润,查询结果如下:
BK_NO etd_pol SUMI(总收入) SUMC(总支出) SUMIC(利润)
001 2007/01/08 300 150 150
002 2007/01/08 350 150 200
各位请帮忙看看这个查询语句应该如何写呢?谢谢!
------解决方案--------------------select BK_NO,sum(case when IC= 'I ' then amount end) as SUMI,sum(case when IC= 'C ' then amount end) as SUMC,(sum(case when IC= 'I ' then amount end) -sum(case when IC= 'C ' then amount end)) as SUMIC from t group by BK_NO
------解决方案--------------------select bk_no,etd_pol,sum(case when ic= 'I ' then amout else 0),sum(case when ic= 'C ' then amout else 0),sum(case when ic= 'I ' then amout else 0)-sum(case when ic= 'C ' then amout else 0) from tablename group by bk_no,ic
------解决方案----------------------试试
select bk_no,etd_opl
,sum(case when ic = 'I ' then amount else 0 end) as 收入
,sum(case when ic = 'C ' then amount else 0 end) as 支出
,sum(case when ic = I then amount else -amount end) as 利润
from t
group by bk_no,etd_opl
------解决方案--------------------我写的效率最高啊,^_^