简体   繁体   中英

SQL Query - Order by issue

When i have duplicate orders in table, the data displays like below. All header records first and then all line records for that particular order.

OrderNo     Column1  
300         Header   
300         Header   
300         Line   
300         Line    
200         Header  
200         Line  
200         Line    

Expected output:

OrderNo     Column1  
300         Header  
300         Line  
300         Header  
300         Line   
200         Header  
200         Line  
200         Line  

I need to export this data in excel file. SO i need a proper sequence of records,ie Order1,Header,Line then Order2 Header,Line How can i achieve this using sql?

You can interleave the headers and lines using row_number() in the order by clause:

select t.*
from t
order by orderno,
         row_number() over (partition by orderno, column1 order by ?);

The ? is for whatever column determines the final ordering among the rows. If you don't care, you can just use orderno .

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