例如,我有一个表test
:
number | text | date1 | date2
1 | a | 2015-02-21 | 2015-02-23
1 | b | 2015-02-22 | 2015-02-23
1 | c | 2015-02-22 | 2015-02-24
1 | d | 2015-02-21 | 2015-02-24
2 | a | 2015-02-21 | 2015-02-21
2 | b | 2015-02-22 | 2015-02-23
我需要最后显示每个数字date1和date2的文本。 期望的结果集:
number | text | date1 | date2
1 | c | 2015-02-22 | 2015-02-24
2 | b | 2015-02-22 | 2015-02-23
正确地工作SELECT:
SELECT
*
FROM
(SELECT
*
FROM
test
ORDER BY
date1 DESC, date2 DESC
) as tab
GROUP BY
number
这总是能正常工作吗?
是否始终显示第一行分组项目中的数据?
答案 0 :(得分:0)
我不确定我是否达到目标,但请尝试此查询:
SELECT
test.number,
test.text,
t1.date1,
t1.date2,
FROM test
RIGHT JOIN
(SELECT
number,
MAX(date1) as date1,
MAX(date2) as date2,
MAX(CASE WHEN date2>=date1 THEN date2 ELSE date1 END) as dateMax
FROM
test
GROUP BY number
) as t1
ON t1.number=test.number
AND (t1.dateMax = test.date1
OR t1.dateMax = test.date2)