简体   繁体   中英

Order by group of columns in SQL Server

My problem is to sort the data from 2 results. The count is same in both resultsets ( now, I have both the resultsets in one, filtered by Source - a or b). I have to display the data such as - for each ID1 & ID2 combination, display them in the source order; source 'a' - first, then source 'b'). Source b may have all null values for the ID1 & ID2 combination; but for sure have a record.

The schema is - Source, ID1, ID2, Name1, Name2.

I wrote a small cursor to handle this and setting the sequence order with a flag. this worked with small amount of data. But for 1000+ records, its taking lot of time.

Try this:

SELECT
  t1.Source,
  t1.Id1,
  t1.ID2,
  t1.Name1,
  t1.Name2,
  ROW_NUMBER() OVER(PARTITION BY ID1, ID2 
                    ORDER BY SortOrder.sortId) rownum
FROM Table1 t1
INNER JOIN
(
   SELECT 1 AS sortId, 'a' Source
   UNION ALL
   SELECT 2, 'b'
) SortOrder ON t1.Source = SortOrder.Source
ORDER BY rownum, SortOrder.sortId;

SQL Fiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM