在下表中,我不知道如何执行此操作,但如何编写为每个唯一的PhoneNumber返回最新行的查询?
PhoneNumber MessageText ReceiveTime
------------- ------------------------ -------------------
+639148186649 Delivery please 2013-03-19 01:12:55
+639148186649 I need this item 2013-03-22 02:15:01
+639148186649 I need more of this item 2013-03-23 12:01:02
+639194357455 How much for this... 2013-03-24 16:36:33
+639194357455 What time do you open? 2013-03-24 17:55:07
答案 0 :(得分:1)
我找到了答案!
SELECT s1.PhoneNumber, s1.MessageText, s1.ReceiveTime FROM mytable s1 LEFT JOIN mytable s2
ON (s1.PhoneNumber = s2.PhoneNumber AND s1.ReceiveTime < s2.ReceiveTime)
WHERE s2.ReceiveTime IS NULL ORDER BY ReceiveTime DESC
答案 1 :(得分:0)
您不能按一列分组并返回其他不依赖于该列的列。有关提示,请参阅this question的答案。
答案 2 :(得分:0)
我认为这应该有用......
SELECT *
FROM PhoneTable
GROUP BY PhoneNumber
HAVING ReceiveTime = MAX(ReceiveTime)
ORDER BY ReceiveTime
..或者您可能需要做这样的事情......
SELECT PhoneNumber, MessageText, ReceiveTime
FROM PhoneTable t
WHERE ReceiveTime = (SELECT MAX(ReceiveTime)
FROM t
GROUP BY PhoneNumber
HAVING PhoneNumber = t.PhoneNumber)