how to create this query

余生长醉 提交于 2019-12-10 16:59:53

问题


how to create a query if i need to include two aggregate function in select row and per each function i need different group by and where conditions in my example i need to returns the playerName, and how many the player win the this can be checked if the results in table game result= first, and how many times he played

but do not know how to deal with two aggregate functions .

simply i want to join the result of this two queries

1.

select playeName,count(*)
from  player,game
where player.playerId=game.playerId and result="first"
group by game.playerId

2.

select count(*)
from game, player
where game.playerId=player.playerId
group by game.playerId

the set of attributes for table game are playerId , result the set of attributes for table player are playerName,playerId

any idea???


回答1:


Use:

  SELECT p.playername,
         SUM(CASE WHEN g.result = 'first' THEN 1 ELSE 0 END),
         COUNT(*)
    FROM PLAYER p
    JOIN GAME g ON g.playerid = p.playerid
GROUP BY p.playername



回答2:


Along with solutions proposed by OMG Ponies and Bnjmn, you can also get desired results by using WITH ROLLUP

select result, count(*)
from game, player
where game.playerId=player.playerId
group by game.playerId, result WITH ROLLUP

Then, on client side, find records with result equals 'first' and and result is null(which is #games played).



来源:https://stackoverflow.com/questions/4473401/how-to-create-this-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!