在SQLite中根据日期对嵌套组进行排序

时间:2015-11-24 07:59:41

标签: sql sqlite android-sqlite

我的表格如下(根据GrandParentParentChild分组):

Child | Parent | GrandParent |       Date
---------------------------------------------------
  2   |    1   |    1        | 2015-11-04 01:30:22 
  3   |    1   |    1        | 2015-11-05 01:30:22 
  4   |    4   |    4        | 2015-11-04 01:31:41 
  5   |    5   |    5        | 2015-11-04 01:31:41 
  7   |    7   |    7        | 2014-08-19 03:45:01 
  88  |    8   |    8        | 2014-08-19 03:45:01 
  90  |    8   |    8        | 2014-08-19 03:45:01 
  97  |    8   |    8        | 2015-03-18 03:45:01 
  704 |    8   |    8        | 2015-03-18 03:45:01 
  27  |   11   |    9        | 2015-10-22 06:42:30 
  28  |   11   |    9        | 2015-10-24 06:42:30 
  30  |   12   |    9        | 2015-11-15 06:42:30 
  31  |   12   |    9        | 2015-11-16 06:42:30 
没有Child

Parent会将自己视为ParentGrandParent

我的目标是订购上表:

    最近日期的
  1. GrandParent群组应位于顶部
  2. GrandParent内,最近日期的Parent群组应位于顶部
  3. Parent内,最近日期的Child应位于顶部
  4. 结果应为:

    Child | Parent | GrandParent |       Date
    ---------------------------------------------------
      31  |   12   |    9        | 2015-11-16 06:42:30 
      30  |   12   |    9        | 2015-11-15 06:42:30
      28  |   11   |    9        | 2015-10-24 06:42:30 
      27  |   11   |    9        | 2015-10-22 06:42:30  
      3   |    1   |    1        | 2015-11-05 01:30:22 
      2   |    1   |    1        | 2015-11-04 01:30:22
      4   |    4   |    4        | 2015-11-04 01:31:41 
      5   |    5   |    5        | 2015-11-04 01:31:41 
      97  |    8   |    8        | 2015-03-18 03:45:01 
      704 |    8   |    8        | 2015-03-18 03:45:01 
      88  |    8   |    8        | 2014-08-19 03:45:01 
      90  |    8   |    8        | 2014-08-19 03:45:01 
      7   |    7   |    7        | 2014-08-19 03:45:01 
    

2 个答案:

答案 0 :(得分:3)

在ORDER BY中使用子查询。

select child, parent, grandparent, date
from mytable
order by
  (select max(date) from mytable grp where grp.grandparent = mytable.grandparent) desc,
  (select max(date) from mytable grp where grp.parent = mytable.parent) desc,
  date desc;

答案 1 :(得分:1)

我想你想要这样的东西:

select t1.* from @t t1
join (select grandparent, max(date) as date from @t group by grandparent) t2 
   on t2.grandparent = t1.grandparent
join (select parent, max(date) as date from @t group by parent) t3 
   on t3.parent = t1.parent
order by t2.date desc, t3.date desc, t1.date desc

您正在加入包含2套的初始表,其中第一组表示每granparent的最大日期,第二组表示每parents的最大日期。

小提琴http://sqlfiddle.com/#!7/f304c/4