Mysql派生表

时间:2012-03-20 14:52:30

标签: mysql

假设我有一个带字段

的mysql表名表
  • 日期
  • ID

值如下:

10, 2012-01-01, 3
9,  2012-01-04, 3
5,  2012-01-07, 3
3,  2012-01-10, 3
10, 2012-01-01, 4 
6,  2012-01-04, 4 
7,  2012-01-07, 4

在单个sql中,如何获取按ID分组的日期排序的最后和第一个值?

我知道如何获得第一个或最后一个

SELECT rank, id FROM 
  (SELECT rank, id FROM table ORDER BY date DESC) s GROUP BY id;

我希望返回的字段可以像:lastrank,firstrank和id。

谢谢

4 个答案:

答案 0 :(得分:0)

我不完全确定我理解你的问题,但无论如何我都会尝试回答。

SELECT min(rank), max(rank), id
  FROM table
  ORDER BY date DESC
  GROUP BY id;

分组时,您可以在结果上使用聚合函数来获取组中的特定样本。

答案 1 :(得分:0)

试试这个:

select id,
  max(if(MyOrder = 1, rank, null)) as FirstRank,
  max(if(MyOrder = 2, rank, null)) as LastRank
from (
    select t1.id, t1.rank, 1 MyOrder from t t1
    left join t t2 on
    t1.id = t2.id and t1.date > t2.date
    where t2.date is null
    union
    select t1.id, t1.rank, 2 from t t1
    left join t t2 on
    t1.id = t2.id and t1.date < t2.date
    where t2.date is null
) s
group by id

此查询以sampla数据作为输入的结果是:

+----+-----------+----------+
| ID | FIRSTRANK | LASTRANK |
+----+-----------+----------+
|  3 |        10 |        3 |
|  4 |        10 |        7 |
+----+-----------+----------+

答案 2 :(得分:0)

尝试此查询 -

SELECT
  t1.*,
  IF(t1.date = t2.min_date, 'FIRSTRANK', 'LASTRANK') rank_type
FROM table_rank t1
  JOIN (
    SELECT id, MAX(date) max_date, MIN(date) min_date FROM table_rank GROUP BY id
    ) t2
    ON t1.id = t2.id AND (t1.date = t2.min_date OR t1.date = t2.max_date)

答案 3 :(得分:0)

参与GROUP_CONCAT(排名ORDER BY日期),并使用SUBSTRING_INDEX。