所以我有这张桌子
CREATE TABLE RaceResult(name char, time int, age int);
INSERT INTO RaceResult (name, time, age) VALUES
('Steve', '12', '33'),
('Tim', '34', '28'),
('Mark', '22', '37'),
('Tom', '21', '30'),
('Cliff', '13', '33'),
('Vini', '17', '28'),
('Matt', '10', '28'),
('Ben', '9', '29'),
('Brandon', '15', '14');
我想创建第4列,根据他们的年龄组将他们排在第1和第2位等等
年龄组
到目前为止我的选择声明是:
SELECT
CASE
WHEN age < '16' and age > 0
THEN 'group1'
WHEN age < '30' and age > 15
THEN 'group2'
WHEN age > '29'
THEN 'group3'
ELSE 0
END as rank, *
FROM RaceResult
ORDER BY time
但不是排名列只是说'组1,2或3'我希望它输出如下:
RESULTS
Name Time Age Rank
===== ==== === ====
Ben 9 29 1
Matt 10 28 2
Steve 12 33 1
Cliff 13 33 2
Brandon 15 14 1
Vini 17 28 3
Tom 21 30 3
Mark 22 37 4
Tim 34 28 4
真的很感激,如果有人能指出我正确的方向
答案 0 :(得分:2)
试试这个。
;WITH cte
AS (SELECT NAME,
time,
age,
CASE
WHEN ( age / 15 ) + 1 < 3 THEN ( age / 15 ) + 1
ELSE 3
END AS [group]
FROM RaceResult)
SELECT NAME,time,age,
Row_number() OVER (partition BY [group] ORDER BY time ) [Rank]
FROM cte
ORDER BY time
答案 1 :(得分:1)
此查询应该执行您想要的操作:
SELECT
age_group.*,
@num := if (@age_group = age_group, @num + 1, 1) rank,
@age_group := age_group as dummy
FROM (
SELECT
RaceResult.*,
@group := CASE
WHEN age < '16' and age > 0
THEN 'group1'
WHEN age < '30' and age > 15
THEN 'group2'
WHEN age > '29'
THEN 'group3'
ELSE 0
END as age_group
FROM RaceResult,
(select @age_group = '', @num = 1) init
ORDER BY age_group, time
) age_group
解决方案基于以下链接的信息:
http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/