我有类似的桌子
+---------------------+-------+
| date_in | title |
+---------------------+-------+
| 2018-01-01 00:00:00 | foo2 |
| 2018-01-02 00:00:00 | bar |
| 2018-01-03 00:00:00 | man |
| 2018-01-04 01:00:00 | foo2 |
| 2018-01-04 02:00:00 | foo |
| 2018-01-04 03:00:00 | foo1 |
| 2018-01-04 04:00:00 | foo2 |
| 2018-01-05 00:00:00 | test |
+---------------------+-------+
我想要的结果是
+---------------------+-------+
| date_in | title |
+---------------------+-------+
| 2018-01-05 00:00:00 | test |
| 2018-01-04 04:00:00 | foo2 | -- see this
| 2018-01-04 01:00:00 | foo2 | -- see this
| 2018-01-04 03:00:00 | foo1 |
| 2018-01-04 02:00:00 | foo |
| 2018-01-03 00:00:00 | man |
| 2018-01-02 00:00:00 | bar |
| 2018-01-01 00:00:00 | foo2 |
+---------------------+-------+
我在下面的查询和其他几个查询中都尝试过,但是不起作用
SELECT
detail.*
FROM
test detail
JOIN ( SELECT min( date_in ) firstdate, title FROM test GROUP BY title ) firstdate ON detail.title = firstdate.title
ORDER BY
firstdate.firstdate,
detail.title,
detail.date_in
但是此查询显示的是相同标题的行,彼此上下,无论日期如何
我希望行仅在同一天显示在彼此的上方
在这里http://sqlfiddle.com/#!9/039aa/6 SQLFiddle与模式。
答案 0 :(得分:3)
似乎您需要按日期(date_in)和标题desc排序
financialYear: "2019-2020"
holidayDate: "2019-06-07"
holidayDescription: "dfghdfh"
holidayType: "RH"
答案 1 :(得分:1)
我认为您实际上是想在每个日期的最晚时间订购标题。在MySQL 8+中,您可以执行以下操作:
SELECT d.*
FROM test d
ORDER BY date(d.date_in),
MAX(d.date_in) OVER (PARTITION BY date(d.date_in), d.title),
d.title desc,
d.date_in ;
在早期版本中,可以使用子查询。这是一种方法:
SELECT d.*
FROM test d
ORDER BY date(d.date_in),
(SELECT MAX(d2.date_in) FROM test d2 WHERE d2.title = d.title AND DATE(d2.date_in) = DATE(d.date_in)),
d.title desc,
d.date_in;
或者,您可以使用显式的JOIN
:
SELECT d.*
FROM test d JOIN
(SELECT d2.title, DATE(d2.date_in) as date, MAX(d2.date_in) as max_date_in
FROM test d2
GROUP BY d2.title, DATE(d2.date_in)
) d2
ON d2.title = d.title AND d2.date = DATE(d.date_in)
ORDER BY date(d.date_in),
d2.max_date_in,
d.title desc,
d.date_in
答案 2 :(得分:-1)
尝试一下:
SELECT
detail.*
FROM
test detail
JOIN ( SELECT min( date_in ) firstdate, title FROM test GROUP BY title ) firstdate ON detail.title = firstdate.title
ORDER BY
DATE(detail.date_in),
detail.title;
从firstdate.firstdate
中删除了DATE(detail.date_in)
并编辑了ORDER BY
。