2012-10-10 46 views
5

其他数据我在SQL表,该表是这样的: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子句中的字段。我已经尝试了许多陈述,其中有许多不同的排列方式,如Ordering By,Group By等,都没有用处。

我试图避免多条语句。

请帮我解决这个问题。

回答

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 
+1

工程就像一个魅力。尽管我不知道JOIN部分的工作原理,但是能否引导我获得良好的资源? –

+1

@SunnyRGupta - 下面是一些资源:[wikipedia-SQL Joins](http://en.wikipedia.org/wiki/Join_%28SQL%29),[编码恐怖SQL连接的可视化解释 - ](http:/ /www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html),[Codeproject - SQL Join的可视化表示](http://www.codeproject.com/Articles/ 33052 /视觉表示的-SQL联接)。此外,我强烈推荐SQL查询的基础知识[SQL查询仅供参考](http://rads.stackoverflow.com/amzn/click/0201433362)。 –

+1

非常感谢,最后一个链接非常有价值:D –

7

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

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 Demo

+0

有什么问题吗?你想知道更多什么? –

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 
+1

与@Mahmoud相同的答案。请避免重复的答案。 –

0
select quote_user, email_adress, max(___sent_at___) from users group by quote_user 

假设最大sent_at correponds与发送的最后一个邮件。

+1

给出错误: 列'email_adress'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。 –

+0

很抱歉,更改'group by quote_user,email_adress'的group by子句应该可以工作。 –

+1

工程,但没有给出所需的输出。实际上,这是我自己尝试的第一个代码。没有工作,所以在几次尝试之后发布在这里。 –