一列排序和分组

时间:2019-05-13 13:51:47

标签: mysql

我想按日期时间字段排序此数据,其后代的电话号码为“分组依据”。

datetime           |telephone|user               |
-------------------|---------|-------------------|
2019-11-15 20:41:43|      123|proident, sunt in  |
2019-10-08 09:49:33|      456|a deserunt mollit  |
2019-08-13 12:38:16|   123334|d tempor incididun |
2019-07-24 21:44:15|123456789|sectetur adipisci  |
2019-06-14 15:03:32|123456789|it, sed do eiusmod |
2019-05-20 07:09:01|   234234|aliqua. Ut enim    |
2019-05-10 23:22:32| 90812345|Lorem ipsum dolor  |
2019-03-25 17:27:37|   123334|fficia deserunt mo |
2019-02-25 22:32:19|      123| labore et dolore  |
2019-02-18 16:01:05|123456789|lit, sed do eiusmo |

我已经尝试过了,但这还不够。

SELECT * FROM(select * from test order by test.`datetime` desc LIMIT 
18446744073709551615) as sub;

例如,我想首先让电话123的日期时间字段以降序顺序重复两次。

datetime           |telephone|user               |
-------------------|---------|-------------------|
2019-11-15 20:41:43|      123|proident, sunt in  |
2019-02-25 22:32:19|      123| labore et dolore  |
2019-10-08 09:49:33|      456|a deserunt mollit  |
2019-08-13 12:38:16|   123334|d tempor incididun |
2019-07-24 21:44:15|123456789|sectetur adipisci  |
2019-06-14 15:03:32|123456789|it, sed do eiusmod |
2019-02-18 16:01:05|123456789|lit, sed do eiusmo |
2019-05-20 07:09:01|   234234|aliqua. Ut enim    |
2019-05-10 23:22:32| 90812345|Lorem ipsum dolor  |
2019-03-25 17:27:37|   123334|fficia deserunt mo |

1 个答案:

答案 0 :(得分:4)

您可以通过将表自连接到每个datetime的最大值为telephone的表中,然后根据这些最大值进行排序,然后再根据实际值进行排序,以实现此结果。该行的datetime值:

SELECT t1.* 
FROM test t1
JOIN (SELECT telephone, MAX(datetime) AS datetime
      FROM test
      GROUP BY telephone) t2 ON t2.telephone = t1.telephone
ORDER BY t2.datetime DESC, t1.datetime DESC

输出:

datetime            telephone   user
2019-11-15 20:41:43 123         proident, sunt in
2019-02-25 22:32:19 123         labore et dolore
2019-10-08 09:49:33 456         a deserunt mollit
2019-08-13 12:38:16 123334      d tempor incididun
2019-03-25 17:27:37 123334      fficia deserunt mo
2019-07-24 21:44:15 123456789   sectetur adipisci
2019-06-14 15:03:32 123456789   it, sed do eiusmod
2019-02-18 16:01:05 123456789   lit, sed do eiusmo
2019-05-20 07:09:01 234234      aliqua. Ut enim
2019-05-10 23:22:32 90812345    Lorem ipsum dolor

Demo on dbfiddle