Distinct 从句在 SQL Server 2005 中不起作用

Distinct Clause not working in SQL Server 2005

我有很多记录将重复的 taskid 分配给多个人,但我想显示不同的记录意味着在 SQL

的输出中只有一个 taskid

以下是我的查询不起作用给我解决方案

SELECT DISTINCT 
    taskid, taskname, person, userid, dept, date, status, monitor, 
    comments, monitor_comments, respondtime, assignedby, 
    reassigncomment, priority,date_complete, followup_date, re_status
FROM
    task
WHERE     
    (status IS NULL)

在你的情况下,结果是不同的,但不是你想要的,因为你只需要不同的任务 ID,那么你应该使用这个:

SELECT DISTINCT taskid
FROM         task
WHERE     (status IS NULL) 

那么结果将是不同的任务 ID。

首先,如果您在名为 task 的 table 中有一个名为 taskid 的列,我认为它 应该 是唯一的 --除非它是一个缓慢变化的维度。

如果不是唯一的,那你就是在求问:你想要哪一行?

无论如何,SQL Server 2005 有一个名为 row_number() 的功能可以解决您的问题:

select t.*
from (select t.*, row_number() over (partition by taskid order by taskid) as seqnum
      from task
     ) t
where seqnum = 1;

这将 return 每个 taskid 一个任意行。如果您有办法优先选择一行而不是另一行,请调整 order by 子句。

我添加了一个列优先级,其中该列的值是相同 TASKID 的 1,而其他列的值为 0,所以我可以找到

SELECT 不同 taskid, taskname, person, userid, dept, date, status, monitor, 评论,monitor_comments,响应时间,分配者, 重新分配评论,优先级,date_complete,followup_date,re_status 从 任务 哪里
(status IS NULL) and (priority='1')