在存在重复项的情况下获取单列的唯一行

时间:2015-06-22 11:33:08

标签: 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   |
+-----------+--------------+

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:3)

您可以使用ROW_NUMBER()COUNT()

;WITH Cte AS(
    SELECT *,
        rn = ROW_NUMBER() OVER(PARTITION BY thread_id ORDER BY [date]),
        cc = COUNT(*) OVER(PARTITION BY thread_id)
    FROM messages
)
SELECT
    thead_id, [date]
FROM Cte
WHERE
    rn = 1
    AND cc > 1