我想使用 orderby 子句构造一个查询。请指教
I want to construct a query using the orderby clause. Please advise
我的数据是这样的:
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
我想按如下所示更改此 table。
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
显示相同ref ID的内容,有Main的内容排在最前面。
最近注册的内容必须在顶部。
也就是我要创建层级。
Select *
from table
order by refId desc, App Type asc, Reg Date desc
我应该像上面那样配置查询吗?
我想你想要:
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;
已测试:
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 |
+--------+--------+----------+------------+------------+
我的数据是这样的:
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
我想按如下所示更改此 table。
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
显示相同ref ID的内容,有Main的内容排在最前面。 最近注册的内容必须在顶部。 也就是我要创建层级。
Select *
from table
order by refId desc, App Type asc, Reg Date desc
我应该像上面那样配置查询吗?
我想你想要:
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;
已测试:
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 |
+--------+--------+----------+------------+------------+