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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 ORDER BY GROUP BY basic question

Author  Topic 

DennisV
Starting Member

2 Posts

Posted - 2009-09-16 : 17:46:26
I don't have a lot of SQL experience, so please bear with me.

Here is a short table example:

1 09/16/09 11:00 12345
2 09/16/09 12:45 12346
3 09/16/09 13:00 14190
4 09/16/09 13:40 12346

Column 1 is the ID, 2 datetime, 3 a report ID number.

Notice the table is sorted on the datetime (but they are entered totally out of datetime sequence).

Also notice rows 2 and 4 have the same report number.

I need to keep the ORDER BY DateTime as close as possible, but I also need to group the rows with the same report number together like so:

1 09/16/09 11:00 12345
2 09/16/09 12:45 12346
4 09/16/09 13:40 12346
3 09/16/09 13:00 14190

Notice row 4 now follows row 2 because the report numbers are the same.

Row 2 must be in the proper datetime order, but any following rows with the same report number can be any date.

I have no idea how to accomplish this.

Thanks for any help,

Dennis




hadi teo
Starting Member

4 Posts

Posted - 2009-09-16 : 18:38:50
Assuming that this is the script to build the table schema

CREATE TABLE [dbo].[Reports](
[ID] [int] NOT NULL,
[CreatedDate] [datetime] NULL,
[ReportID] [int] NULL
) ON [PRIMARY]


You can achieve the result by issuing ORDER BY ReportID column, subsequently followed by CreatedDate column

so in summary, the correct sql query is :

SELECT * FROM reports
ORDER BY ReportID, CreatedDate

Go to Top of Page

DennisV
Starting Member

2 Posts

Posted - 2009-09-17 : 13:29:00
Thanks, I tried that first.

The problem is the dates will be completely unsorted.

I need to keep the dates sorted except when there are duplicate report ID numbers.

And the first report ID number always needs to be sorted in the proper date. Other dates in the group of duplicate report ID numbers do not need to be sorted.
Go to Top of Page
   

- Advertisement -