Click here to Skip to main content
15,882,114 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
if i have a table containing three columns, with some records, I want to select records in which column 1 and column3 comes once if they are multiple times

That means distinct column1 and column3



For Better Understanding

XML
column1 column2 column3
user1   a1  category1
user2   a2  category2
user1   a3  category2
user1   a4  category1
user3   a5  category2


Output

column1 column2 column3
user1   a1  category1
user2   a2  category2
user1   a3  category2
user3   a5  category2
Posted
Updated 1-Apr-14 10:02am
v3
Comments
Richard C Bishop 1-Apr-14 15:26pm    
You literally used the word to use in your query(distinct).
binadi007 1-Apr-14 15:29pm    
distinct check on the basis of the first column if available 2nd column then distinct check according to 2nd column and so on
thats why i m not able to get right output
I think view be solution but not getting it from view
a little thinking about stored procedure can anyone help me regarding it
Richard C Bishop 1-Apr-14 15:30pm    
I see, yeah that is tricky.
binadi007 1-Apr-14 15:30pm    
can anyone write a snippet for better understanding......thanks in advance
Maciej Los 1-Apr-14 15:35pm    
Please, see my answer. Sample data would be helpfull. Please, improve your question. Use "Improve question" widget.

1 solution

You can count via ROW_NUMBER() function and only ROW_NUMBER() with value = 1 you need to select.

Your query will look something like:
SQL
Select Column1, Column2, Column3
FROM
(
    SELECT ROW_NUMBER() over (Partition By Column1, Column3 Order by Column1, Column3) as Rownr, Column1, Column2, Column3
    FROM Table1
) as DataSet
where Rownr = 1
 
Share this answer
 
v3
Comments
binadi007 1-Apr-14 15:49pm    
I didn't get the output that i mentioned above as an example
Even I got a column with name Rownr and value in it be 1
Herman<T>.Instance 1-Apr-14 16:00pm    
Did you execute both selects ? Or only the inner? The inner statement pre selects your data, the outer statement the requested columns.
Herman<T>.Instance 1-Apr-14 16:02pm    
you were right. The columns Column1, Column2, Column3 were not set in the inner select. See my changes
binadi007 1-Apr-14 16:06pm    
in this a problem is that when running internal select command rownr column added extra with value 1,2,3 and so on and when execute both select command then output will only one record having rownr = 1
Herman<T>.Instance 1-Apr-14 16:16pm    
I changed my query, so both queries have the three needed columns. But you need both statements in the way I have created. Only then you will see your three columns as distinct. So Select and SubSelect and not two selects after each other.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900