我有一个查询,最终看起来像这样:
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
现在我的要求是标记最高等级,以便前端可以突出显示该记录。我对其他想法持开放态度,但尝试了这一点,并没有达到预期的效果。所以,如果你能指出我做错了什么,或者提到另一种方式,我将不胜感激。
SELECT
Team,
StatCount,
TeamRank,
(
CASE
WHEN MAX(StatCount) = StatCount
THEN 'True'
ELSE
'False'
END
) AS 'HighScore'
FROM Rank
ORDER BY Team DESC;
谢谢
我的错误!
DDL对于每个条目都有'AAA',但它们是不同的。应该是'AAA','BBB','CCC'等。
谢谢大家的答案。我再次为糟糕的DDL数据道歉。
答案 0 :(得分:2)
尝试
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
答案 1 :(得分:2)
以下是将Max
与Partition By
结合使用的一种方式(假设您使用的是SQL 2005或更高版本):
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;
答案 2 :(得分:2)
怎么样:
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