在我的表格中,我有以下栏目:
CRMID | user | ticket_id | | description | date | hour
我想要做的是从表中选择所有行,但是当两个(或更多)行具有相同的ticket_id
时,我只希望最新的行出现在结果中,所以以最新的日期和小时排。
这里的问题是我应该添加案例,如果日期列中的值相同,那么我将比较小时列,否则,它的简单警告我将只比较日期列。
答案 0 :(得分:2)
SELECT
n.*
FROM
table n RIGHT JOIN (
SELECT
MAX(date) AS max_date,
(SELECT MAX(hour) AS hour WHERE date = max_date) AS hour,
user,
ticket_id
FROM
table
GROUP BY
user,
ticket_id
) m ON n.user = m.user AND n.ticket_id = m.ticket_id
答案 1 :(得分:0)
您可能希望合并日期和小时列,然后执行比较
SELECT foo.*
FROM foo
JOIN (SELECT ticket_id, MAX(ADDTIME(`date`,`hour`)) as mostrecent
FROM foo
GROUP BY ticket_id) AS bar
ON bar.ticket_id = foo.ticket_id
and bar.mostrecent = ADDTIME(foo.`date`,foo.`hour`);