Sql server 把一个日期分成两个日期

Sql server 把一个日期分成两个日期,sql-server,sql-server-2008,Sql Server,Sql Server 2008,我想把两个日期分成四个日期: Date1:04/01/2012 Date2:12/05/2015 我想要的结果是 If datepart(year,date2)=datepart(year,getdate()) Case1 Date1:04/01/2012 Date2:31/12/2014 Date3:01/01/2015 Date4:12/05/2015 Else Case2 Date1:04/01/2012 Date2:12/05/2015 我的问题是如何在案例1中获取日期2和日期3?您

我想把两个日期分成四个日期:

Date1:04/01/2012
Date2:12/05/2015
我想要的结果是

If datepart(year,date2)=datepart(year,getdate())
Case1
Date1:04/01/2012
Date2:31/12/2014
Date3:01/01/2015
Date4:12/05/2015
Else
Case2
Date1:04/01/2012
Date2:12/05/2015

我的问题是如何在案例1中获取日期2和日期3?

您可以这样创建它们:

select '01/01/'+(select cast(datepart(yy,getdate()) as varchar))
select '31/12/'+(select cast(datepart(yy,getdate())-1 as varchar))

如果我理解正确,您希望在select语句中添加“假”记录,前提是第一个日期在当前年份之前,第二个日期在当前年份。
我冒昧地假设,如果第一个日期实际上是去年的12月31日,您不想添加31/12/

以下是我的建议:

;With cte as (
SELECT DateValue, ROW_NUMBER() OVER (ORDER BY DateValue) As rn
FROM Tbl
)

-- Get the first date
SELECT DateValue
FROM cte 
WHERE rn = 1

UNION ALL

/*
  Add the last date of the previous year. 
  The where clause will enable you to add this to the select result only on your terms
  (if the second date is on the current year and the first date is before Dec 31th of the last year)
*/
SELECT CAST(CAST(YEAR(GETDATE())-1 as varchar) + '-12-31' as date)
FROM cte 
WHERE rn = 2
AND YEAR(DateValue) = YEAR(GETDATE())
AND CAST(CAST(YEAR(GETDATE())-1 as varchar) + '-12-31' as date) > (SELECT DateValue FROM cte WHERE rn = 1)

UNION ALL

/*
  Add the first date of the current year. 
  Note that the where clause here is only testing that the second date is on the current year, 
  while the first date is before the current year. 
  So it will add the Jan 1st of the current year even if the first date is Dec 31th of the last year.
*/
SELECT CAST(CAST(YEAR(GETDATE()) as varchar) + '-01-01' as date)
FROM cte 
WHERE rn = 2 
AND YEAR(DateValue) = YEAR(GETDATE())
AND YEAR(GETDATE()) > (SELECT YEAR(DateValue) FROM cte WHERE rn = 1)

UNION ALL

-- add the second date
SELECT DateValue
FROM cte WHERE rn = 2

谢谢,但我需要一个解决方案,无论日期格式如何!