I have a query that in the end looks like this:
DECLARE @Rank TABLE
(
Team VARCHAR(3),
StatCount TINYINT,
TeamRank TINYINT
)
INSERT INTO @Rank VALUES ('AAA', 10, 5)
INSERT INTO @Rank VALUES ('AAA', 7, 4)
INSERT INTO @Rank VALUES ('AAA', 6, 3)
INSERT INTO @Rank VALUES ('AAA', 4, 2)
INSERT INTO @Rank VALUES ('AAA', 2, 1)
SELECT * From @Rank ORDER BY TeamRank DESC
Now my requirement is to mark the highest rank so that the front end can highlight that record. I am open to other ideas but tried this out of the gate and it's not quite behaving as expected. So if you could point out what I am doing wrong or as mentioned another way I would be grateful.
SELECT
Team,
StatCount,
TeamRank,
(
CASE
WHEN MAX(StatCount) = StatCount
THEN 'True'
ELSE
'False'
END
) AS 'HighScore'
FROM Rank
ORDER BY Team DESC;
Thank You
MY Mistake!
DDL had 'AAA' for every entry but they are different. Should be 'AAA','BBB','CCC' etc.
Thank You everyone for your answers. I apologize again for the bad DDL data.
Try
SELECT
Team,
StatCount,
TeamRank,
(
CASE
WHEN StatCount = (select max(StatCount) from @Rank)
THEN 'True'
ELSE
'False'
END
) AS 'HighScore'
FROM @Rank
ORDER BY Team DESC
Here's one way using Max
with Partition By
(assuming you're using SQL 2005 or greater):
SELECT
Team,
StatCount,
TeamRank,
CASE
WHEN MAX(StatCount) OVER (PARTITION BY Team) = StatCount
THEN 'True'
ELSE
'False'
END
AS 'HighScore'
FROM @Rank
ORDER BY Team DESC;
what about:
SELECT
r.*, isnull(v.b, 0) HighScore
From
@Rank r
left join (select max(StatCount) m, 1 b from @Rank) v on r.StatCount = v.m
ORDER BY TeamRank DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.