sql - 按存在重复项的单列获取唯一行

标签 sql sql-server

我有以下名为 messages 的数据库表,其中包含以下列:

thread_id, sender_id, receiver_id, date

例子:

+-----------+------------+-------------+-------------+
| thread_id | sender_id  | receiver_id |  date       |
+----------------------+-----------+-----------------+
|   1       | 1          |  2          | 11/06/2015  |
|   1       | 2          |  1          | 14/06/2015  |
|   1       | 1          |  2          | 14/06/2015  |
|   1       | 2          |  1          | 20/06/2015  |
|   2       | 1          |  3          | 12/06/2015  |
|   3       | 4          |  2          | 19/06/2015  |
|   3       | 2          |  2          | 20/06/2015  |
+-----------+------------+-------------+-------------+

我需要一个查询,该查询将按最早日期选择唯一的 thread_id 并且 thread_id 存在不止一次。

所以我想要的结果是:

+-----------+--------------+
| thread_id |   date       |
+-----------|--------------+
|   1       | 11/06/2015   |
|   3       | 19/06/2015   |
+-----------+--------------+

最佳答案

SELECT 
    MIN(date),thread_id 
FROM 
    messages 
GROUP BY 
    thread_id 
HAVING 
    COUNT(thread_id) > 1

关于sql - 按存在重复项的单列获取唯一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30978929/

相关文章:

sql-server - SQL Server 2005 数字精度损失

c# - 从 C# 中的另一个类调用 ConnectionString

php - Mysql 子选择查询优化

sql - 在多个查询上使用 "with"语句?

sql-server - 从给定表动态构建外键图查询

sql - 使用左连接的 SUM 得到错误的结果

sql - 如何找到访问SQL Server的用户名和机器名

忽略空字符串列的mysql group_concat

php - 使用mysql从单个查询中的两个不同表中进行选择

mysql - 用子字符串替换列的值(未知长度)