My data looks like this:
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
7 null Main 2017-05-20
I would like to change this table as shown below.
App ID Ref Id App Type Reg Date
7 null Main 2017-05-20
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
The contents with the same ref ID are displayed, and the content with the Main is positioned at the top. The most recently registered content must be at the top. That is, I want to create a hierarchy.
I configured the query as shown below.
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;
However, the results are as follows. I am sorting by Reg Date even if Ref Id is null. In conclusion, to be configured as the second table, data 7 should be at the top.
App ID Ref Id App Type Reg Date maxdate
4 2 Main 2017-05-15 2017-05-15
2 2 Sub 2017-05-14 2017-05-15
5 3 Main 2017-05-14 2017-05-14
1 1 Main 2017-05-13 2017-05-13
6 1 sub 2017-05-17 2017-05-13
3 1 Sub 2017-05-16 2017-05-13
7 null Main 2017-05-20 null