SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Order By Tricks
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

rypi
Yak Posting Veteran

51 Posts

Posted - 05/29/2012 :  17:57:54  Show Profile  Reply with Quote
I have what seems to be a strange results order question.

Using the following test table and query;

declare @TestTable table (
ID int,
ProjectId int,
HoursEntered decimal (18,2)
)

insert into @TestTable(
ID,
ProjectId,
HoursEntered
)
values 
(1, 5, 5.0),
(2, 2, 2.0),
(3, 5, 2.0),
(4, 4, 1.0),
(5, 2, 3.0)

SELECT 
	T.ID,
	T.ProjectId,
	T.HoursEntered
FROM
	@TestTable T
ORDER BY
	ProjectId

The folowwing results are returned:

ID	ProjectId	HoursEntered
2	    2	           2.00
5	    2	           3.00
4	    4	           1.00
1	    5	           5.00
3	    5	           2.00

However, I need the results to be returned like so:

ID	ProjectId	HoursEntered
1	    5	           5.00
3	    5	           2.00
2	    2	           2.00
5	    2	           3.00
4	    4	           1.00

The ProjectId's need to be listed together, but the ID needs to be ascending as much as the projectId allows.

How can the query be written so the data is returned like that?
Are there any tricks using the Order By clause possibly?

Thanks.

visakh16
Very Important crosS Applying yaK Herder

India
47140 Posts

Posted - 05/29/2012 :  21:08:49  Show Profile  Reply with Quote

SELECT ID,
ProjectId,
HoursEntered
FROM
(
SELECT 
	T.ID,
	T.ProjectId,
	T.HoursEntered,
        MIN(T.ID) OVER (PARTITION BY T.ProjectId) AS MinID
FROM
	@TestTable T
)R
ORDER BY
	MinID,ID


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

rypi
Yak Posting Veteran

51 Posts

Posted - 05/30/2012 :  00:21:28  Show Profile  Reply with Quote
Works perfectly!!

Thanks visakh
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
47140 Posts

Posted - 05/30/2012 :  15:36:17  Show Profile  Reply with Quote
wc

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000