2017-05-31 52 views
-2

我的數據是這樣的:我想使用orderby子句構造一個查詢。請指教

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 

我應該像上面那樣配置查詢嗎?

+2

「順序」 是不明確的:沒有任何列既不上升也不下降。 – alfasin

+0

從表 中選擇* order by refId desc,Ref_ID,App Type asc,Reg Date desc – uSeruSher

+0

@uSeruSher你是說Ref_ID和App Type都按asc排序? –

回答

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 | 
+--------+--------+----------+------------+------------+ 
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;