在视图中排列项目编号,MYSQL

时间:2013-11-25 18:50:09

标签: mysql sql

我通过以下声明创建了一个视图。

CREATE VIEW
view_projectHour
AS
SELECT pno
, SUM( hours ) AS total_hours
FROM works_on
GROUP BY pno
ORDER BY total_hours DESC

现在,我如何在此视图中实现排名?我希望项目排名。具有最高小时数的项目必须排名为1并置于顶部,依此类推。还有相同时间的项目。

2 个答案:

答案 0 :(得分:2)

不幸的是,MySQL缺乏对分析功能的支持。特别是RANK()RANK_DENSE()

要模仿RANK()你可以做

SELECT pno, total_hours, rank
  FROM
( 
  SELECT pno, total_hours,
         @n := @n + 1 rnum, @r := IF(@h = total_hours, @r, @n) rank, @h := total_hours
    FROM
  (
    SELECT pno, SUM(hours) total_hours
      FROM works_on 
     GROUP BY pno
  ) q CROSS JOIN (SELECT @n := 0, @r := 0, @h := NULL) i
   ORDER BY total_hours DESC, pno
) t

示例输出:

| PNO | TOTAL_HOURS | RANK |
|-----|-------------|------|
|   3 |          61 |    1 |
|   1 |          40 |    2 |
|   2 |          40 |    2 |
|   4 |          10 |    4 |

要模仿DENSE_RANK()你可以做

SELECT pno, total_hours, rank
  FROM
(
  SELECT pno, total_hours,
         @r := IF(@h = total_hours, @r, @r + 1) rank, @h := total_hours
    FROM
  (
    SELECT pno, SUM(hours) total_hours
      FROM works_on 
     GROUP BY pno
  ) q CROSS JOIN (SELECT @r := 0, @h := NULL) i
   ORDER BY total_hours DESC, pno
) t

示例输出:

| PNO | TOTAL_HOURS | RANK |
|-----|-------------|------|
|   3 |          61 |    1 |
|   1 |          40 |    2 |
|   2 |          40 |    2 |
|   4 |          10 |    3 |

注意: 如果您不介意在结果集中添加一个或两个额外的列,则可以抛弃外部SELECT

这是 SQLFiddle 演示

答案 1 :(得分:1)

另一种解决方案是使用JOIN来计算每行中排名更好的值的数量;

SELECT 1+COUNT(b.total_hours) rank, a.pno, a.total_hours
FROM test a
LEFT JOIN test b
  ON a.total_hours < b.total_hours
GROUP BY a.pno, a.total_hours
ORDER BY total_hours DESC;

An SQLfiddle to test with