Tuesday, October 5, 2010

How can I force SQL Server Group By to respect column order when grouping?

Programmer Question

I am using SQL Server 2005.



SEE END OF THIS POST REGARDING BAD TABLE DESIGN.



I have two columns. I would like to group by the first column with respect to the order of the second column. Microsofts documentation states that GROUP BY clause does not care about order, how can I enforce this??



Here is my pseudo query:



SELECT col_1,
MIN(col_2),
MAX(col_2)
FROM someTable
GROUP BY col_1 (*** WITH RESPECT TO ORDER OF col_2***)


If I ran the query on the following table:



Col_1    Col_2
A 1
A 2
A 3
B 4
C 5
C 6
B 7
A 9


I should get the following results:



Col_1  Min   Max
A 1 3
B 4 4
C 5 6
B 7 7
A 9 9


The key part is that I CAN NOT have all 4 records of A lumped together in the result set. When the table/subquery is queried against, it is sorted by col_2, each new instance of col_1 should result in a new grouping. Thanks, I could not find anything on this.



I can do NOTHING with the table design. This was a table that was created by an outside vendor that is used with their proprietary software. I repeat I can do nothing about the table design!!!!



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails