Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Order By Tricks

Author  Topic 

rypi
Yak Posting Veteran

55 Posts

Posted - 2012-05-29 : 17:57:54
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

52326 Posts

Posted - 2012-05-29 : 21:08:49
[code]
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
[/code]

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

Go to Top of Page

rypi
Yak Posting Veteran

55 Posts

Posted - 2012-05-30 : 00:21:28
Works perfectly!!

Thanks visakh
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-05-30 : 15:36:17
wc

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

Go to Top of Page
   

- Advertisement -