TSQL ROW_NUMBER()OVER(PARTITION BY ... ORDER BY ....)

时间:2017-11-15 21:18:36

标签: tsql row-number

我可以在没有分区的情况下进行row_number吗? (见帖子末尾的数据)我可以用这个语句来获得一个ORDER#。

     ROW_NUMBER() OVER (PARTITION BY LOG_ID ORDER BY ORDER_ID) 

获取LOG#的任何建议?

-LOG#   ORDER#  LOG_ID  ORDER_ID
-1      1       340580  387373215
-1      2       340580  387373225
-2      1       340925  387812330
-3      1       340935  388093450
-4      1       340945  387615845
-5      1       340990  386433405
-6      1       341675  376247120
-6      2       341675  376247130
-6      3       341675  388352445

2 个答案:

答案 0 :(得分:1)

SELECT
    - DENSE_RANK() OVER (ORDER BY LOG_ID) AS "#LOG",
    ROW_NUMBER() OVER (PARTITION BY LOG_ID ORDER BY ORDER_ID) AS "#ORDER",
    LOG_ID,
    ORDER_ID
FROM UnnamedTable

答案 1 :(得分:1)

declare @yourtable table ([ORDER#] int, LOG_ID int, ORDER_ID bigint);
insert @yourtable values
(1,340580,387373215),
(2,340580,387373225),
(1,340925,387812330),
(1,340935,388093450),
(1,340945,387615845),
(1,340990,386433405),
(1,341675,376247120),
(2,341675,376247130),
(3,341675,388352445);


select [-LOG#] = -dense_rank() over (order by LOG_ID), *
from @yourtable;

<强>返回

-LOG#                ORDER#      LOG_ID      ORDER_ID
-------------------- ----------- ----------- --------------------
-1                   1           340580      387373215
-1                   2           340580      387373225
-2                   1           340925      387812330
-3                   1           340935      388093450
-4                   1           340945      387615845
-5                   1           340990      386433405
-6                   1           341675      376247120
-6                   2           341675      376247130
-6                   3           341675      388352445

编辑:@bacon bits击败了我。 :(