我有一个像这样的mysql表:
Tbl
[Username Number Type]
manos 5 A
manos 6 B
maria 2 A
maria 3 B
maria 1 C
nick 7 A
nick 4 C
aaron 8 A
我想创建一个视图,我将按每个类型中的其他用户比较,按Type
分组,每个用户的排名(按较大的数字)。更具体地说,我希望输出为:
[Username Rank Type]
manos 3 A
manos 1 B
maria 4 A
maria 2 B
maria 2 C
nick 2 A
nick 1 C
aaron 1 A
我尝试了以下内容:
select Username, count(*) as Rank, Type
from Tbl as aw
where
Number <= (
select Number
from Tbl
where Type = aw.Type
)
group by Username, Type
结果是我收到Subquery returns more than 1 row
错误。
任何帮助将不胜感激!
编辑:根据建议更改了列的名称。也是帮助的小提琴:http://sqlfiddle.com/#!9/55ec3f
编辑2:对“所有组合排名”的一些澄清和更正。
假设我们有另一个名为Teams
的表:
Teams
[Username Team]
manos T1
manos T2
maria T1
maria T2
nick T1
nick T2
aaron T3
在这种情况下,我想提取组和类型的每个组合的排名,即我想要的马诺斯:
答案 0 :(得分:1)
为了理智,我重命名了您的group
列...
SELECT username
, user_group
, number
, CASE WHEN @prev=user_group THEN @i:=@i+1 ELSE @i:=1 END rank
, @prev:=user_group
FROM my_table x
, (SELECT @prev:=null, @i:=0) vars
ORDER
BY user_group
, number DESC;
答案 1 :(得分:-1)
正确的代码:
select Username, (select Number
from Tbl as t
where t.Type = aw.Type and t.Username = aw.Username) as Rank, Type from Tbl as aw where
Number <= (
select Number
from Tbl as t
where t.Type = aw.Type and t.Username = aw.Username
) group by Username, Type