Click here to Skip to main content
15,879,239 members
Please Sign up or sign in to vote.
3.86/5 (4 votes)
See more:
I have the following dataset

type id	value
1       a
1	b
2	c
2	d
3	e
3	f
1	g
3	h
2	i

I want to write a query to display the following result

type id	value
1	a
2	c
3	e
1	b
2	d
3	f
1	g
2	i
3	h
Posted
Updated 20-Dec-12 13:10pm
v2
Comments
Christian Graus 20-Dec-12 19:59pm    
I'm not sure this is possible without doing it in code. It's a reasonably complex rule, I think. The numbers only matter in each group, they don't have an absolute worth. You also assume that there's no pair that has duplicate letters.
chaau 20-Dec-12 20:22pm    
It is possible now. With the help of OVER PARTITION BY clause.I had to learn it myself just recently for a project I was working on.
chaau 20-Dec-12 20:05pm    
for some stupid reason I can't submit the solution.

select *
from dataset
order by row_number() over (partition by type_id order by value), type_id

SQL Fiddle:
http://sqlfiddle.com/#!3/0004d/17
chaau 20-Dec-12 20:11pm    
looks like I could finally post my solution. codeproject is slow today for some reason
Christian Graus 21-Dec-12 16:11pm    
Thanks - that is awesome. That's my homework over xmas.

1 solution

SQL
select *
from dataset
order by row_number() over (partition by type_id order by value), type_id


Please check the SQL Fiddle[^]
 
Share this answer
 
Comments
[no name] 20-Dec-12 20:12pm    
it worked, thanks a lot man :)
chaau 20-Dec-12 20:23pm    
BTW, it is a very good interview question. I recommend you learn more about this OVER PARTITION BY clause
[no name] 21-Dec-12 10:39am    
I had been working with rownumber for long before posting this here. Learnt the real meaning of partition by :) practicing now with different dataset :)
__TR__ 21-Dec-12 5:30am    
My 5!

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