Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Sorting Data into a Pattern

Tags:

Not sure if this is possible, but there might be a creative approach...

Given this data in SQL Server 2005:

AAA
AAA
BBB
BBB
CCC
CCC
DDD
DDD

How could I return a result set sorted in a pattern like this:

AAA
BBB
CCC
DDD
AAA
BBB
CCC
DDD

like image 688
Daniel Avatar asked Feb 14 '10 23:02

Daniel


People also ask

How can you perform pattern matching in SQL?

SQL pattern matching enables you to use _ to match any single character and % to match an arbitrary number of characters (including zero characters). In MySQL, SQL patterns are case-insensitive by default. Some examples are shown here. Do not use = or <> when you use SQL patterns.

How do I create a SQL query for sorting?

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Which SQL condition is used for pattern matching in a query?

Generally, the REGEXP_LIKE(column_name, 'regex') function is used for pattern matching in SQL. SQL also supports some operators that work similar to this function, these are: 'REGEXP' and 'RLIKE' operator.

Can you arrange the result-set of an SQL query on multiple columns?

Can you arrange the result set of an SQL query on multiple columns? If you specify multiple columns, the result set is sorted by the first column and then that sorted result set is sorted by the second column, and so on.


1 Answers

If your column were called "col", and your table were named "table", I would try something like this:

WITH Indexes AS (
    SELECT 
    ROW_NUMBER() OVER (PARTITION BY col ORDER BY col) as __row,
    col
    FROM table)
SELECT col
FROM Indexes
ORDER BY __row, col;
like image 127
Dave Markle Avatar answered Oct 03 '22 18:10

Dave Markle