简体   繁体   中英

Distinct Clause not working in SQL Server 2005

I have so many records having duplicate taskid assigned to multiple person, but i want to show distinct records means only one taskid in output in SQL

Below is my query not working give me solution

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)

in your case, result is distinct but not of your desire because you need only distinct task id then you should use this:

SELECT DISTINCT taskid
FROM         task
WHERE     (status IS NULL) 

then result would be distinct task ids.

First, if you have a column called taskid in a table called task , I think it should be unique -- unless it is somehow a slowly changing dimension.

If it is not unique, then you are begging the question: which row do you want?

In any case, SQL Server 2005 have a function called row_number() that can solve your problem:

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

This will return one arbitrary row for each taskid . If you have a way of preferring one row over another, then adjust the order by clause.

i have added a column priority in which the value of that column is 1 of same TASKID and other will be 0 so i can find

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) and (priority='1')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM