按两个日期列对视图排序并添加排名列

时间:2013-07-31 14:21:00

标签: mysql sql

我有一个类似下面的mysql表。

id  name    firstDate   secondDate
==  =====   =========   ==========
A1  Carol   2000-07-24  1956-07-24
A2  Victor  2000-07-24  1980-01-13
A3  Paul    1999-12-10  1985-01-10
A4  Mia     2000-06-17  1945-10-22
A5  Luke    2000-07-24  1960-03-19

我需要使用以下格式创建视图:

  1. firstDate 列按升序排序。

  2. 如果两个或多个记录在 firstDate 列上具有相同的值,那么这些记录将使用 secondDate 列来确定女巫记录将被放置在第一个,第二个和第二个等等。

  3. secondDate 列后面会添加一列等级,并且会有一个连续的数字。

  4. 喜欢这个

    id  name    firstDate   secondDate   rank
    ==  =====   =========   ==========   ====
    A3  Paul    1999-12-10  1985-01-10   1
    A4  Mia     2000-06-17  1945-10-22   2
    A1  Carol   2000-07-24  1956-07-24   3
    A5  Luke    2000-07-24  1960-03-19   4
    A2  Victor  2000-07-24  1980-01-13   5
    

    作为

2 个答案:

答案 0 :(得分:0)

试试这个

    SET @rank := 0;
    SELECT * , @rank := @rank + 1 AS rank FROM
    (
    SELECT id , name  ,  firstDate  , secondDate
    from table1
     ORDER BY firstDate  asc, secondDate asc
    ) zz

DEMO HERE

或者

   SELECT * , @rank := @rank + 1 AS rank FROM
  (
  SELECT id , name  ,  firstDate  , secondDate
  from table1
   ORDER BY firstDate  asc, secondDate asc
   ) zz, (SELECT @rank := 0) z;

DEMO HERE

答案 1 :(得分:0)

你可以简化echo_Me的回答:

SET @rank := 0;
SELECT id , name  ,  firstDate  , secondDate , @rank := @rank + 1 AS rank 
FROM table1
ORDER BY firstDate  asc, secondDate asc

请参阅http://sqlfiddle.com/#!2/24a8d/7