在SQL Server Select中按连续编号排序

时间:2015-04-08 17:57:26

标签: sql sql-server-2008

我想知道是否有办法按SQL Server 2008中的连续数字排序。

目前我有

Select DISTINCT StoreNum, StoreName, Date, Time
From tbl_stores
ORDER BY StoreNum, Date

哪会给我

1 | Toronto Store  | 2015-03-04 | 12:44:44 |
1 | Toronto Store  | 2015-03-04 | 12:44:45 |
2 | Chatham Store  | 2015-03-05 | 12:44:47 | 
2 | Chatham Store  | 2015-03-05 | 12:44:48 | 
3 | London Store   | 2015-03-06 | 12:44:51 |
3 | London Store   | 2015-03-06 | 12:44:52 |

是否可以按StoreNum连续排序,然后按日期排序?喜欢这个

1 | Toronto Store   | 2015-03-04 | 12:44:44 |
2 | Chatham Store   | 2015-03-05 | 12:44:47 | 
3 | London Store    | 2015-03-06 | 12:44:51 |
1 | Toronto Store   | 2015-03-04 | 12:44:45 |
2 | Chatham Store   | 2015-03-05 | 12:44:48 | 
3 | London Store    | 2015-03-06 | 12:44:52 |

最新尝试:

  SELECT DISTINCT StoreNum, StoreName, Date, Time,(
    Select StoreNum, StoreName, Date, Time,
           row_number() over (partition by StoreNum order by Date, Time) as seqnum
    From tbl_stores AS q
    order by seqnum, StoreNum, Date,Time
    )
    FROM q

1 个答案:

答案 0 :(得分:1)

这是一个想法(但没有distinct)。使用row_number()枚举每个商店中的值,然后按顺序排序:

Select StoreNum, StoreName, Date, Time,
       row_number() over (partition by StoreNum order by Date, Time) as seqnum
From tbl_stores
order by seqnum, StoreNum, Date;

编辑:

类似的东西:

Select StoreNum, StoreName, Date, Time,
       row_number() over (partition by StoreNum order by Date, Time) as seqnum
From (select distinct StoreNum, StoreName, Date, Time
      from tbl_stores s
     ) s
order by seqnum, StoreNum, Date;