我在SQL Server数据库中有这些表:
用户:
Nick CodCountry BirthDate
-----------------------------------
Chekov 1 2001-09-15
Kirk 1 1982-01-27
McCoy 3 2002-02-12
Scott 3 2001-03-31
Spock 2 2002-02-12
Sulu 4 1991-05-02
Uhura 2 1989-12-21
播放:
Nick CodTrivia MoneyEarned
----------------------------------
Chekov 2 5
Kirk 1 500
Kirk 3 400
Kirk 4 200
Kirk 7 300
McCoy 2 15
McCoy 6 10
Scott 6 25
Spock 2 50
Spock 6 50
Sulu 1 200
Sulu 4 500
Sulu 7 500
Uhura 3 200
Uhura 7 0
我需要赢得更多trivias的用户。 moneyearned> 0是胜利
到目前为止,我有这个:
select *
from Users
where Nick in (select Nick
from Play
where MoneyEarned > 0
group by Nick
having count(Nick) = (select top 1 count(Nick)))
但是那之后我的思绪一片空白......有人可以帮助我吗?
Pd:它需要向Kirk展示,因为他赢了4次。答案 0 :(得分:0)
将play
表格按nick
分组并计算获胜金额。使用TOP 1 ... ORDER BY COUNT(1)
检索最佳的。
;WITH BestPlayer AS
(
SELECT TOP 1
P.Nick
FROM
Play AS P
WHERE
P.MoneyEarned > 0
GROUP BY
P.Nick
ORDER BY
COUNT(1) DESC, -- Amount of wins
SUM(MoneyEarned) DESC -- Amount of money
)
SELECT
U.*
FROM
Users AS U
INNER JOIN BestPlayer AS B ON U.Nick = B.Nick
如果您想要显示具有相同排名的玩家,可以添加WITH TIES
。 (TOP 1 WITH TIES
)