-2
SELECT DATEPART(YEAR, PURCHASE_DATE) AS TRANSACTION_YEAR, DATEPART(MONTH, PURCHASE_DATE) AS TRANSACTION_MONTH,
CASE WHEN DATEPART(YEAR, DUE_DATE) >= DATEPART(YEAR, PURCHASE_DATE) THEN DATEPART(YEAR, DUE_DATE)
ELSE DATEPART(YEAR, PURCHASE_DATE) END AS RELEASE_YEAR, 
CASE WHEN (DATEPART(YEAR, DUE_DATE) = DATEPART(YEAR, PURCHASE_DATE) AND DATEPART(MONTH, DUE_DATE) >= DATEPART(MONTH, PURCHASE_DATE)) THEN DATEPART(MONTH, DUE_DATE)
WHEN DATEPART(YEAR, DUE_DATE) > DATEPART(YEAR, PURCHASE_DATE) THEN DATEPART(MONTH, DUE_DATE)
ELSE
DATEPART(MONTH, PURCHASE_DATE) END AS RELEASE_MONTH,
CAST(YEAR(CASE WHEN DATEPART(YEAR, DUE_DATE) >= DATEPART(YEAR, PURCHASE_DATE) THEN DATEPART(YEAR, DUE_DATE)
ELSE DATEPART(YEAR, PURCHASE_DATE) END) AS VARCHAR(4)) + RIGHT('0'+CAST(MONTH(CASE WHEN (DATEPART(YEAR, DUE_DATE) = DATEPART(YEAR, PURCHASE_DATE) AND DATEPART(MONTH, DUE_DATE) >= DATEPART(MONTH, PURCHASE_DATE)) THEN DATEPART(MONTH, DUE_DATE)
WHEN DATEPART(YEAR, DUE_DATE) > DATEPART(YEAR, PURCHASE_DATE) THEN DATEPART(MONTH, DUE_DATE)
ELSE
DATEPART(MONTH, PURCHASE_DATE) END) AS VARCHAR(2)),2)
FROM TEST

在包含六条记录的样本表上生成

2012    1   2012    1   190501
2012    1   2013    12  190501
2011    1   2012    1   190501
2011    1   2011    1   190501
2012    1   2012    1   190501
2012    1   2012    2   190501

我究竟做错了什么?

非常感谢!

4

2 回答 2

2

我认为问题在于您已经在使用CASE表达式提取月份和年份组件 - 并将这些表达式的结果传递给YEARandMONTH函数 - 期望传递一个datetime值。因此,您正在将 s 隐式转换intdatetime值。

SELECT YEAR(2012)

----
1905

SELECT MONTH(12)

----
01

当 anint隐式转换为 adatetime时,它实际上是自 以来的天数19000101。大约 2000 天之后的大多数日子都19000101发生在 1905 年。


话虽如此,这一切看起来都比它需要的复杂得多 - 使用子查询,您可以执行一次适当的计算,而不必重复它们 - 初始输入是什么,您的目标是最终输出为了?

于 2012-07-07T13:48:04.963 回答
0

你为什么要一口气做完所有事情并在整个地方重复自己。

如果你从

select 
DatePart(YEAR,PURCHASE_DATE) as PURCHASE_YEAR,
DatePart(YEAR,DUE_DATE) as DUE_YEAR,
DatePart(MONTH,PURCHASE_DATE) as PURCHASE_MONTH,
DatePart(MONTH,DUE_DATE) as DUE_MONTH
From Test

然后你可以做

SELECT PURCHASE_Year AS TRANSACTION_YEAR, 
       PURCHASE_Month) AS TRANSACTION_MONTH,
       CASE 
       WHEN DUE_YEAR >= PURCHASE_YEAR THEN DUE_YEAR
       ELSE PURCHASE_YEAR
       END AS RELEASE_YEAR, 
       CASE 
       WHEN (DUE_YEAR = PURCHASE_YEAR) AND (DUE_MONTH >= PURCHASE_MONTH) THEN DUE_MONTH
       WHEN DUE_YEAR > PURCHASE_YEAR THEN DUE_MONTH
       ELSE PURCHASE_MONTH 
       END AS RELEASE_MONTH,
       CAST(
        CAST(RELEASE_YEAR As VarChar(4)) + 
        '-' + 
        CAST(RELEASE_MONTH as VarChar(2)) + 
        '-1' as DATE) as RELEASE_DATE
FROM (
select 
DatePart(YEAR,PURCHASE_DATE) as PURCHASE_YEAR,
DatePart(YEAR,DUE_DATE) as DUE_YEAR,
DatePart(MONTH,PURCHASE_DATE) as PURCHASE_MONTH,
DatePart(MONTH,DUE_DATE) as DUE_MONTH
From Test
) SomeDummyTableName

我想这就是你所追求的,我什至可能在涉过那个泥沼之后就得到了它。

于 2012-07-07T14:05:06.343 回答