行号Tsql

时间:2016-02-25 10:09:44

标签: sql tsql

我有以下语法

NSArray *obj-image=@[@"Test.png",@"Test.png",@"Test.png"];
NSArray *obj-title=@[@"Test",@"Test",@"Test"];
NSArray *obj-subtitle=@[@"Test",@"Test",@"Test"];
NSDictionary * obj_dictionary ={ image : obj_image, title:obj_title, subtitle:obj_subtitle}
NSArray * obj_array= [obj_dictionarry];

这是我有两个日历(CalenderID 1 = Weekly,CalenderID 2 = Monthly)这是RentCalendar表。

每个租金日历都有一个年份(RentCalendarYear表),​​而每年每年都有一组期间。

enter image description here

你会注意到第47行,最后一列被标记为1(真)这是因为它是当前时期。

我需要做的是为任何CalendarId标记前12个句点。我想知道我是否能用ROW_NUMBER实现这个目标,当前CurrentPeriod WHERE = 1将为1,之前的所有时段将开始编号为2,3,4,5,依此类推。

我不知道怎么做。

2 个答案:

答案 0 :(得分:1)

这样的事情:

 SELECT * FROM (
 select rcp.CalendarPeriodId,rc.CalendarId,rcp.CalendarYearId,rcp.PeriodNumber,rcp.PeriodStartDate,rcp.PeriodEndDate,
   ROW_NUMBER() OVER(ORDER BY PeriodStartDate DESC) AS CurrentPeriod
from RentCalendarPeriod rcp
LEFT JOIN RentCalendarYear rcy ON rcy.CalenderYearId = rcp.CalendarYearId
LEFT JOIN RentCalendar rc ON rc.CalendarId = rcy.CalendarId)
WHERE currentperiod <= 12

我不确定我是否理解正确...这将为您提供最新的第1周,第二个第二个,第三个第3个等等,在CurrentPeriod列中

答案 1 :(得分:0)

这样的事情:

;WITH CTE AS (
   SELECT rcp.CalendarPeriodId, rc.CalendarId, rcp.CalendarYearId, 
          rcp.PeriodNumber, rcp.PeriodStartDate, rcp.PeriodEndDate,
          ROW_NUMBER() OVER (ORDER BY rcp.CalendarPeriodId) AS rn,
          CASE 
             WHEN GETDATE() BETWEEN rcp.PeriodStartDate AND 
                                    rcp.PeriodEndDate THEN 1 
             ELSE 0 
          END AS 'CurrentPeriod'
   FROM RentCalendarPeriod rcp
   LEFT JOIN RentCalendarYear rcy ON rcy.CalenderYearId = rcp.CalendarYearId
   LEFT JOIN RentCalendar rc ON rc.CalendarId = rcy.CalendarId
)
SELECT CalendarPeriodId, CalendarId, CalendarYearId,
       PeriodNumber, PeriodStartDate, PeriodEndDate,
       'CurrentPeriod',
       (t.rn + 1) - c.rn AS rn
FROM CTE AS c
CROSS JOIN (SELECT rn FROM CTE WHERE 'CurrentPeriod' = 1) AS t
WHERE rn BETWEEN t.rn - 11 AND t.rn

这将返回12条记录,其中包含CurrentPeriod = 1之前的 11条记录。字段rn枚举从具有CurrentPeriod = 1的记录开始的记录。