Paresh
Paresh

Reputation: 3749

Want data from table in SQL server

I have table data like this


id id1  name
1  1    test1
1  1    test1
1  2    test2
2  1    test1
2  2    test2
3  1    test1
3  2    test2
3  2    test2

now from table i want the data as below like for id = 1 order by id1 asc the first name = test1 so i want the first two row

id id1  name
1  1    test1
1  1    test1

not third row

For id=2 order by id1 asc the first name = test1 so i want first row as test1 has assign only ones for id=2

id id1  name
2  1    test1

And for id=3 same as id=2

Please suggest me how can get the perticlur value for ID , because the scenerio is differnt for ID=1

Upvotes: 0

Views: 99

Answers (4)

Anthony Faull
Anthony Faull

Reputation: 17957

Use RANK() or DENSE_RANK() to get the first ranked rows, including duplicates, for each id.

select * from (
    select *, dense_rank() over (partition by [id] order by [id2]) as ranking
    from [table]
) as t
where ranking = 1

Upvotes: 1

nanda
nanda

Reputation: 24788

select * from [table] where id = 1 and name like "test1" order by id1

Upvotes: 0

Andrew M
Andrew M

Reputation: 9459

Perhaps this:

select * from [table] where id = 1 order by id1

I think the point is that you can use one column in the where clause, and a different column in the order by clause. that's no problem.

But I'm not sure you could actually have the data table you describe, because the first two rows are identical (how can SQL tell them apart? Or more technically, there'd be a primary key violation)?

Upvotes: 0

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

Sounds to me like you just want select * from [tablename] where id1 = 1, but I might be wrong. I find the question a bit, well, vague...

Upvotes: 0

Related Questions