5

我在 SQL 中有一个表,该表是这样的:

+-------------+---------------+-------------------------+
| quotes_user | email_address | ________Sent_at________ |
+-------------+---------------+-------------------------+
| user1       | email1        | 2012-10-09 12:23:53.253 |
| user1       | email2        | 2012-10-09 12:24:53.253 |
| user2       | email3        | 2012-10-09 13:20:53.253 |
| user2       | email4        | 2012-10-09 11:23:53.253 |
| user3       | email5        | 2012-10-08 10:29:53.253 |
| user3       | email6        | 2012-10-08 14:23:53.253 |
+-------------+---------------+-------------------------+

我希望结果显示

+-------------+---------------+-------------------------+
| quotes_user | email_address | ________Sent_at________ |
+-------------+---------------+-------------------------+
| user1       | email2        | 2012-10-09 12:24:53.253 |
| user2       | email3        | 2012-10-09 13:20:53.253 |
| user3       | email6        | 2012-10-08 14:23:53.253 |
+-------------+---------------+-------------------------+

即我想选择唯一用户列表,以及与他们关联的最新电子邮件地址。

另一种解释问题的方法是,我想选择一个不包含在任何聚合函数或 order by 子句中的字段。我已经尝试了许多具有 Distinct 和 Order By、Group By 等排列的语句,但没有用。

我试图避免多个陈述。

这个你能帮我吗。

4

4 回答 4

7

Sent_AT查询背后的想法是在子查询中为每个查询获取最大值quotes_user并将其连接回原始表。

SELECT  a.*
FROM    tableName a INNER JOIN
        (
            SELECT  quotes_user, MAX(Sent_AT) maxSENT
            FROM tableName
            Group By quotes_user
        ) b on a.quotes_user = b.quotes_user AND
                a.Sent_AT = b.maxSent

SQLFiddle 演示

于 2012-10-10T06:54:05.710 回答
1

试试这个:

SELECT t2.quotes_user, t2.email_address, t2.Sent_at AS '________Sent_at________'
FROM
(
   SELECT quotes_user, MAX(Sent_at) AS MaxDate
   FROM Table 
   GROUP BY quotes_user
) t1
INNER JOIN Table t2 ON  t1.quotes_user = t2.quotes_user 
                    AND t1.Sent_at = t2.MaxDate
于 2012-10-10T06:54:13.763 回答
0
 select quotes_user, email_address, sent_at 
 from table_name t1 inner join
   (select quote_user, max(sent_at) as sent
    from table_name group by quotes_uaser) t2  
 on t1.quotes_user = t2.quotes_user and t1.sent_at = t2.sent
于 2012-10-10T06:55:18.597 回答
0
select quote_user, email_adress, max( ___sent_at___ ) from users group by quote_user 

假设最大的 sent_at 对应于最后发送的邮件。

于 2012-10-10T06:56:04.487 回答