How to force SQL Server Group to use column order when grouping?

I am using SQL Server 2005.

SEE THE END OF THIS MAIL FOR THE BAD TABLE PROJECT.

I have two columns. I would like to group by the first column in the order of the second column. Microsoft documentation claims the GROUP BY clause doesn't care about the order, how can I ensure 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 run the query in 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 CANNOT have all 4 A records put together in the result set. When a table / subquery is requested, it is sorted by the col_2 command, each new instance of col_1 should lead to a new grouping. Thank you, I could not find anything.

. , , . , !!!!

+3
3
;WITH T
     AS (SELECT Col1,
                Col2,
                DENSE_RANK() OVER (ORDER BY Col2) - 
                   DENSE_RANK() OVER (PARTITION BY Col1 ORDER BY Col2) AS G
         FROM   YourTable)
SELECT Col1,
       MIN(Col2) AS [Min],
       Max(Col2) AS [Max]
FROM   T
GROUP  BY Col1,
          G
ORDER  BY [Min] 
+8

, , .

, , . col_1, seried_id.

, , , -. , , , , .

, , , , proc , toegther . , , , - ( , , ).

, , , col_1, col_2 . , , , , .

+2

, :

col1    (No column name)    (No column name)
A   1   9
B   4   7
C   5   6

, MAX (col2), , "" , , . , .

DECLARE @SomeTable TABLE (Col1 CHAR(1), Col2 INT)

INSERT INTO @SomeTable(Col1, Col2) VALUES('A', 1)
INSERT INTO @SomeTable(Col1, Col2) VALUES('A', 2)
INSERT INTO @SomeTable(Col1, Col2) VALUES('A', 3)
INSERT INTO @SomeTable(Col1, Col2) VALUES('B', 4)
INSERT INTO @SomeTable(Col1, Col2) VALUES('C', 5)
INSERT INTO @SomeTable(Col1, Col2) VALUES('C', 6)
INSERT INTO @SomeTable(Col1, Col2) VALUES('B', 7)
INSERT INTO @SomeTable(Col1, Col2) VALUES('A', 9)

SELECT col1, 
       MIN(col2), 
       MAX(col2)
FROM @SomeTable 
GROUP BY col1
0

Source: https://habr.com/ru/post/1768102/


All Articles