2014-06-05 35 views
1

逐年遞增,對所有記錄如果我有這樣的數據:更新日期,由ID

create table t (PID int identity, 
         AwardDate date, 
         PytUnits int, 
         PytDate date, 
         AwardID int); 

insert into t values 
('1/1/2014', '5', '1/1/2014', 1), 
('1/1/2014', '5', '1/1/2015', 1), 
('1/1/2014', '5', '1/1/2016', 1), 
('1/1/2014', '5', '1/1/2012', 2), 
('1/1/2014', '5', '1/1/2013', 2), 
('1/1/2014', '5', '1/1/2014', 2), 
('1/1/2014', '5', '1/1/2015', 2) 
; 

(see this in SQL Fiddle)

我怎樣才能更新PytDate,如果是> Today's date,首日的下一個月的第一個記錄,併爲每個記錄後增加1年,每AwardID

重要提示:數據庫實際上是MS Access,但我小提琴是在SQL服務器上用作示例,並希望生成一個答案,我可以運行並轉換爲Access SQL。

回答

1

在TSQL中最簡單的方法是使用公用表表達式。但MSAccess不具備此功能。因此,下面的TSQL,雖然它在SQL Server 2008及更高版本中工作,但不適用於MSaccess。如果你需要一個MSAccess查詢來做到這一點,那麼讓我知道。創建一個子例程可能會更簡單。

;with Awards(NewDate, RowID, AwardRowId, PID, 
          AwardDate , 
          PytUnits, 
          PytDate , 
          AwardID) --CTE Syntax set up columns 
    as 
    (select NewDate = case when PytDate> getdate() then convert(varchar(7), convert(date, dateadd(month, 1, getdate())))+'-01' else PytDate end --Generate a new date based on the rules provided in question i.e. for future dates use next month, this is temporary value as we override it in the output if the other rule is met this row is only used for the first row 
    , RowID = ROW_NUMBER() over (order by PID) --RowID is simple row number for each row of output based on PID which is Primary key 
    , AwardRowId = DENSE_Rank() over (order by AwardId) --Generate a RowID based on AwardId for each change in AwardID as it comes to us 
    , * --all other columns 
    FROM t where PytDate> getdate() --we are only interested in future dated data 
    ) 
    Select CalcDate = case RowID 
     when 1 then NewDate         --first row is special use the next month value 
     else dateadd(year, AwardRowId,  AwardDate) end --other rows get a new date based on the row position by Award and we add a year for each change in AwardId to the base award date 
    , * 
    from Awards 
    order by PID 

如果你想在MSACCESS來模擬這一點,你可以創建4個查詢,其中連鎖這個邏輯一起

查詢1 - 獲取FirstOfNextMonth作爲簡單的計算和查找未來紀錄 QUERY2 - 獲取獎勵 QUERY3清單 - 生成DenseRank Query4 - 結果

查詢1 SELECT T *,IIF([pytdate]>現在(),DateSerial(年份(DATEADD( 「M」,1,[pYTDATE])),月(DATEADD(。 「m」,1,[PYTDATE])),1),[PYTDATE])AS FirstOfMonth,[pytdate]> N ow()AS IsFuture FROM t WHERE((((t.PytDate)> Now()));

QUERY2 SELECT Query1.AwardID FROM查詢1 GROUP BY Query1.AwardID ORDER BY Query1.AwardID;

QUERY3 SELECT A.AwardId,COUNT(*)AS DENSE_RANK FROM QUERY2作爲左JOIN QUERY2 AS B開B.AwardId < = A.AwardId GROUP BY A.AwardId;

Query4 SELECT查詢1 *,IIF([DENSE_RANK] = 1,[FirstOfMonth],使用DateAdd( 「YYYY」,[DENSE_RANK],[pytdate]))AS NewDate,Query3.dense_rank FROM查詢1 INNER JOIN QUERY3 ON Query1.AwardID = Query3.AwardId ORDER BY Query3.dense_rank,Query1.PytDate;

+0

感謝您的回答 - 它確實幫助我將一些邏輯串在一起。話雖如此,你認爲你可以在你的答案中添加一些註釋來解釋「TSQL」代碼嗎?我一直在一塊一塊地看着它,但在這裏也有好處。 –