我有一個table_changes(Id,stard_date,end_date),我想添加兩列rank_end_date
和new_end_date
。SQL中的IF語句
我有我的數據的問題是,並不總是有連續性(當月水平,白天在一個月是不是在我intrest)end_date
和start_date
剛過它(未來之間見例如1 ),所以我需要在某些情況下使用「strech」end_date
,因此在本月的級別會有連續性。
對於例1,所述new_end_date
是1/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
莫非
在實現結果任何人的幫助?
你使用的是MySQL還是SQL-Server? –
也許這是一個使用SQL過程的gd想法。 – Mox
你可以很容易地使用CASE語句來做到這一點,就像if else else一樣。 – sagi