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

求一SQL语句。
有一个表
type   money     gameID
1         100         10
2         200         10
1         50           10
1         100         20
2         50           20

需要写一个视图
group   by   出GAMEID
的支出和收入
type=1   表示支出
2表示收入
要求效果为  
gameID   getmoney   getcount   outmoney   outcount

------解决方案--------------------
getmoney 和 outmoney 可以这样求,

SELECT gameID, SUM(CASE type WHEN 1 THEN money ELSE 0 END) getmoney, SUM(CASE type
WHEN 2 THEN money ELSE 0 END) outmoney FROM test GROUP BY gameID


getcount, outcount 还想到,不知道这样可不可以

SELECT gameID, COUNT(CASE type WHEN 1 THEN 1 END) getcount, SUM(CASE type
WHEN 2 THEN 1 END) outcount FROM test GROUP BY gameID

如果不可以,我能想到的只有使用递归变量了,就无法一条sql了,
等待高人出现
------解决方案--------------------
select gameid,
sum(case when type=1 then money else 0 end) as getmoney,
sum(case when type=1 then 1 else 0 end)as getcount,
sum(case when type=2 then money else 0 end) as outmoney,
sum(case when type=2 then 1 else 0 end) as outcount
group by gameid