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
我究竟做错了什么?
非常感谢!