我的数据如下:
App ID Ref Id App Type Reg Date
1 1 Main 2017-05-13
2 2 Sub 2017-05-14
3 1 Sub 2017-05-16
4 2 Main 2017-05-15
5 3 Main 2017-05-14
6 1 sub 2017-05-17
我想更改此表,如下所示。
App ID Ref Id App Type Reg Date
4 2 Main 2017-05-15
2 2 Sub 2017-05-14
5 3 Main 2017-05-14
1 1 Main 2017-05-13
6 1 sub 2017-05-17
3 1 Sub 2017-05-16
显示具有相同参考ID的内容,并且具有Main的内容位于顶部。 最近注册的内容必须位于顶部。 也就是说,我想创建一个层次结构。
Select *
from table
order by refId desc, App Type asc, Reg Date desc
我应该像上面那样配置查询吗?
答案 0 :(得分:0)
我想你想要:
select t.*
from t
order by (select max(t2.regdate) from t t2 where t2.refid = t.refid) desc,
t.refid,
(t.apptype = 'Main') desc,
t.regdate desc;
答案 1 :(得分:0)
测试了它:
SELECT *
FROM t
JOIN (SELECT `Ref Id`, MAX(`Reg Date`) AS maxdate FROM t WHERE `App Type` = 'Main' GROUP BY 1) md USING(`Ref Id`)
ORDER BY maxdate DESC, `Ref Id`, (`App Type` = 'Main') DESC;
+--------+--------+----------+------------+------------+
| Ref Id | App ID | App Type | Reg Date | maxdate |
+--------+--------+----------+------------+------------+
| 2 | 4 | Main | 2017-05-15 | 2017-05-15 |
| 2 | 2 | Sub | 2017-05-14 | 2017-05-15 |
| 3 | 5 | Main | 2017-05-14 | 2017-05-14 |
| 1 | 1 | Main | 2017-05-13 | 2017-05-13 |
| 1 | 6 | sub | 2017-05-17 | 2017-05-13 |
| 1 | 3 | Sub | 2017-05-16 | 2017-05-13 |
+--------+--------+----------+------------+------------+