2013-07-07 47 views
1

这有点难以解释,所以我会一步一步来做。下面是我创建的表格。Mysql排名排行

id | item_1 | item_2 | item_3| 
32 | 1 | 43 | 54 | 
32 | 54 | 32 | 32 | 
67 | 42 | 45 | 12 | 

正如你所看到的,前两排具有相同的ID,我的目标是,让第一行是(1 + 43 + 54)的总和,而第二行的总和是(54 + 32 + 32),然后添加具有相同ID的两行并从高到低排序。我设法用下面的代码来做到这一点。但是如果我想获得该行的position,如下表所示。我基本上正在做一些排名系统,我首先通过item_sum命令他们,然后获取行的位置。我怎样才能实现它?

position | id | item_sum | 
    1 | 32 | 218 | 
    2 | 67 | 99 | 

select 
     id, 
     sum(item_1+item_2+item_3) as item_sum 
from yourtable 
group by id 
order by item_sum desc; 

我试着做下面这段代码:但位置号码不按顺序排列,因为我通过“item_sum”

SET @position=0; 
SELECT @position:= @position+1 AS position, 
      id, 
      sum(item_1+item_2+item_3) as item_sum 
    from yourtable 
    group by id 
    order by item_sum desc; 
+0

所以你期望返回的结果是:'32 - 216,67 - 99'? – BenM

+1

id 32的总数是216.它是218吗? –

+0

称为'id'('identifier'的缩写)的列应该是一个独特的属性。所以不应该有多个具有相同ID的行。如果有,那么这个列不是一个id。 –

回答

0

假设我理解正确你的问题设置的顺序,这应该工作精细:

SELECT `yourtable`.`id` AS `id`, 
     `count`.`total` AS `item_count` 
FROM `yourtable` 
LEFT JOIN (
    SELECT `id`, SUM(`item_1` + `item_2` + `item_3`) AS `total` 
     FROM `yourtable` GROUP BY `id` 
) `count` ON `count`.`id` = `yourtable`.`id` 
GROUP BY `yourtable`.`id` 
ORDER BY `count`.`total` DESC 

以上将返回:

+--------+------------+ 
| id | item_count | 
+--------+------------+ 
| 32 | 216  | 
| 67 |  99  | 
+--------+------------+ 

请参阅SQLFiddle demo以进行全面的工作演示。

+0

我想要一个排名系统,如1行=位置1,行2 =位置2,行3 =位置3,依此类推...... – user2310422

+0

这就是它给你的......你只需要添加你自己的计数? – BenM

+0

是的,我需要添加自己的计数,您没有在代码中指定 – user2310422

2

你已经提出这个问题了。我以前给过答。其实不知道你的要求是什么......

SELECT @rn:[email protected]+1 AS position, item_sum , id 
FROM (
    select 
     id, 
     sum(item_1+item_2+item_3) as item_sum 
from yourtable 
group by id 
order by item_sum desc 
) t1, (SELECT @rn:=0) t2; 

一看便知。 Here look for what you need