SQL GROUP BY没有保持正确的顺序

时间:2016-08-30 16:45:24

标签: mysql sql

我有一个表,我正在运行此查询:

SELECT datetime, from_email, from_name
FROM emails
WHERE user_seq = '1'
GROUP BY from_email
ORDER BY datetime DESC

查询执行并返回数据,但它没有按datetime DESC

的顺序显示数据

当我删除GROUP BY时,数据会以正确的顺序显示。

2 个答案:

答案 0 :(得分:4)

您似乎正在使用mysql,因为它允许您排除聚合中未包含的group by子句中的字段,在本例中为datetime字段。考虑到你想对datetime降序进行排序,也许你真的需要使用max

SELECT max(datetime), 
       from_email, 
       from_name 
FROM emails 
WHERE user_seq = '1' 
GROUP BY from_email, from_name
ORDER BY 1 desc

答案 1 :(得分:1)

我想,您想使用from_email对结果进行分组。请尝试使用以下脚本..并且该脚本适用于SQL Server ..

;WITH cte_1
as( SELECT datetime, from_email, from_name
           , ROW_NUMBER ()OVER(PARTITION BY from_email ORDER BY datetime desc) RNo
     FROM emails
     WHERE user_seq = '1')
SELECT datetime, from_email, from_name
FROM cte_1
WHERE RNO=1

以下代码似乎可以在MySql中运行..

SELECT datetime, from_email, from_name
FROM emails e
 JOIN (SELECT from_email,MAX(datetime) MaxDate
       FROM emails
       GROUP BY from_email)t on e.from_email=t.from_email AND e.datetime=t.MaxDate