将日期分为两个日期

时间:2015-06-05 22:49:56

标签: 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

我的问题如何在case1中获取date2和date3?

2 个答案:

答案 0 :(得分:0)

您可以像这样创建它们:

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

答案 1 :(得分:0)

如果我理解正确的话,如果第一个日期是在当前年份之前的一年中,而第二个日期是在当前年份,那么您希望在您的选择语句中添加“假”记录。
如果第一个日期实际上是去年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

You can see it working on this fiddle.

相关问题