Lifewithsun
Lifewithsun

Reputation: 998

SQL select distinct data without ordering the column

I have table which contains data as below:

DECLARE @CheckList TABLE
                   (  
                        RowNumber INT IDENTITY(1,1) INT, 
                        CheckId INT, 
                        Treat INT 
                   )  
INSERT INTO @CheckList 
VALUES (1, 1, 1), (1, 3, 1), (1, 2, 1), (1, 1, 1),
       (1, 3, 1), (1, 2, 1), (1, 1, 3), (1, 3, 3),
       (1, 2, 3);

SELECT DISTINCT Id, CheckId 
FROM @CheckList
WHERE Id = 1

Where I want to select the data from this table as

   Id   CheckId
   ------------
    1   1
    1   3
    1   2

I want the same order of the check id which is available in table. Can you help me with this?

Upvotes: 0

Views: 87

Answers (2)

Arpit Srivastava
Arpit Srivastava

Reputation: 9

you can check this

DECLARE @CheckList TABLE
               (  Id INT ,  CheckId INT, Treat INT )  
INSERT INTO @CheckList 
VALUES (1, 1, 1), (1, 3, 1), (1, 2, 1), (1, 1, 1),(1, 3, 1), (1, 2, 1), (1, 1, 3),(1,3,3), (1, 2, 3);

SELECT DISTINCT Id, CheckId 
FROM @CheckList
WHERE Id = 1

Upvotes: -1

Serg
Serg

Reputation: 22811

Retain original ordering by RowNumber identity column

select Id,CheckId
from(
   select distinct Id,CheckId, min(rownumber) over(partition by Id,CheckId) rn
   from @CheckList
   where Id=1
   ) t
order by rn;

Db fiddle

Upvotes: 7

Related Questions