实现行号()

时间:2014-11-10 10:36:29

标签: sql sql-server sql-server-2008 window-functions

如何在不使用函数本身的情况下在sql server中实现row_number()窗口函数,可能在索引表上加入?

或更多,我该如何实施

select ROW_NUMBER() OVER(PARTITION BY ATLAS_USER_ID ORDER BY Event_Time DESC) AS RR

分区上的行号而不使用此功能?

分区是否像分组一样?

3 个答案:

答案 0 :(得分:0)

您可以添加

这样的列
ID int IDENTITY(1,1)

答案 1 :(得分:0)

试试这个..试一试不确定这是你想要的。请注意,这需要一个标识列。

CREATE TABLE #TableName
    ([Id] int,[Dates] datetime)
;

INSERT INTO #TableName
    ([Id], [Dates])
VALUES

    (1, '2014-08-07 00:00:00'),
    (2, '2014-08-07 00:00:00'),
    (3,  '2014-08-07 00:00:00'),
    (4,  '2014-08-07 00:00:00'),
    (5, '2014-08-08 00:00:00'),
    (6,'2014-08-08 00:00:00'),
    (7, '2014-08-08 00:00:00'),
    (8,  '2014-08-09 00:00:00'),
    (9, '2014-08-09 00:00:00'),
    (10, '2014-08-09 00:00:00'),
    (11, '2014-08-10 00:00:00'),
    (12, '2014-08-10 00:00:00'),
    (13, '2014-08-10 00:00:00')


SELECT CASE
         WHEN [Id]%cn = 0 THEN cn
         ELSE [Id]%cn
       END,
       *
FROM   #TableName a
       JOIN (SELECT Count(1) cn,
                    [Dates]
             FROM   #TableName
             GROUP  BY [Dates]) b
         ON a.[Dates] = b.[Dates] 

更新:

添加大小写,只需在where子句中添加相同的case语句。

SELECT CASE
         WHEN Id%cn = 0 THEN cn
         ELSE Id%cn
       END,
       *
FROM   atlas_events a
       JOIN (SELECT Count(1) AS cn,
                    Event_Time
             FROM   atlas_events
             GROUP  BY Event_Time) b
         ON a.Event_Time = b.Event_Time
WHERE  PRT_PROJECT_ID = 175
       AND ADV_PROJECT_ID = 713
       AND event_type = 1
       AND CASE
             WHEN [Id]%cn = 0 THEN cn
             ELSE [Id]%cn
           END = 5 

答案 2 :(得分:0)

假设每行中都有唯一标识符,您可以使用相关子查询或apply获得相同的功能。如果事件时间不同:

select t.*,
       (select count(*)
        from table t2
        where t2.ATLAS_USER_ID = t.ATLAS_USER_ID and
              t2.Event_Time <= t.EventTime
       )
from table t;

如果它们不相同,但行中还有另一个id:

select t.*,
       (select count(*)
        from table t2
        where t2.ATLAS_USER_ID = t.ATLAS_USER_ID and
              (t2.Event_Time < t.Event_Time or
               t2.Event_Time = t.Event_Time and t2.id <= t.id
              )
       )
from table t;