2016-01-17 51 views
1

我有一個table_changes(Id,stard_date,end_date),我想添加兩列rank_end_datenew_end_dateSQL中的IF語句

我有我的數據的問題是,並不總是有連續性(當月水平,白天在一個月是不是在我intrest)end_datestart_date剛過它(未來之間見例如1 ),所以我需要在某些情況下使用「strech」end_date,因此在本月的級別會有連續性。

對於例1,所述new_end_date1/2/2015,並且不必須是28/2/2015。如果排名1中的end_date早於31/12/2015則將其排列爲31/12/9999

一些例子:

Ex1: 
Id --start date --end_date --rank_end_date new_end_date 
111 01/01/1970  1/1/1980   2    1/2/2015 
111 01/03/2015  31/12/9999  1    31/12/9999 


Ex2: 
Id --start_date --end_date --rank_end_date new_end_date 
111 01/01/1970 1/1/1980   1   31/12/9999 

Ex3: 
Id --start_date --end_date --rank_end_date new_end_date 
111 01/01/1970 1/1/1980   2   01/05/1990 
111 01/05/1990 31/12/1995  1   31/12/9999 

Ex4: 
Id --start_date --end_date --rank__end_date new_end_date 
111 01/03/2015  31/12/9999  1   31/12/9999 

Ex5: 
Id --start_Date --end_date  --rank__end_date new_end_date 
111 01/02/2015 31/5/2015    2    01/5/2015 
111 01/06/2015 31/12/9999   1    31/12/9999 

語法應該是這樣的,但我不知道怎麼寫那些IF語句SQL

if rank_end_date ==2 then new_end_date == 1/Month(start_date(rank_end_date - 1)) - 1 /2015 
if rank_end_date ==1 then new_end_date == 31/12/2015 
else new_end_date = end_date 

    Select [Id],[StartDate],[EndDate], 
    Rank_End_Date, case 
    when t.Rank_End_Date = (2) **then 
    CAST(CAST(Year([StartDate]) AS varchar) + '-' + CAST(Month([StartDate]) AS varchar) + '-' + 
--How to do I choose the Start_Date from the record with Rank==1? It is selecting 
the start date from the record with rank==2 ofcourse. 

    CAST(Day ([EMER_StartDate]) AS varchar) AS DATE) 
    when t.Rank_End_Date = (1) then '9999-12-31' 
    else t.[EMER_EndDate] end As New_End_Date 
    from ( 
    Select [Id],[StartDate],[EndDate], 
    Rank() OVER (PARTITION BY [Id] order by [EndDate] desc) as Rank_End_Date 
    from [dbo].[Changes] 
    ) t 
莫非

在實現結果任何人的幫助?

+3

你使用的是MySQL還是SQL-Server? –

+0

也許這是一個使用SQL過程的gd想法。 – Mox

+0

你可以很容易地使用CASE語句來做到這一點,就像if else else一樣。 – sagi

回答

0

如果我已經理解你的問題並且你只能在rank_end_date爲1或2的值,那麼類似這個查詢的東西應該給你你正在尋找的答案。無論哪種方式,LEAD(或LAG函數,如果您按升序對記錄進行排序)將允許您從不同的記錄中獲取值。

SELECT ID 
    , start_date 
    , end_date 
    , rank_end_date 
    , CASE WHEN rank_end_date = 1 THEN 
      CASE WHEN end_date < '31/12/2005' THEN '31/12/9999' ELSE end_date END 
     WHEN rank_end_date = 2 THEN LEAD(start_date,1) OVER(ORDER BY ID, rank_end_date DESC) 
     END AS new_end_date   
FROM dbo.Changes 
0

不能使用SQL Server 2008中LEAD OR LAG功能,所以你可以嘗試這種解決方案。

with CTE as 
( 
    Select [Id] as ID,[StartDate] as StartDate,[EndDate] as EndDate, 
    ROW_NUMBER() OVER (PARTITION BY [Id] order by [StartDate] DESC) as rn_Start_Date 
    from [dbo].[Changes] 
) 

Select C1.[Id] , C1.[StartDate], C1.[EndDate], C1.rn_Start_Date as Rank_end_date, 
     ISNULL(DATEADD(MONTH, DATEDIFF(MONTH, 0, C2.[StartDate])-1, 0), cast('9999-12-31' as DATE)) As New_End_Date 
From CTE C1 
    LEFT JOIN CTE C2 ON C1.[ID] = C2.[ID] AND C1.Rn_Start_Date = C2.Rn_Start_Date + 1