我的任务是计算NUMBERS
列和SHIP_DATES
列中月和会计年度的差异。在计算之前,我无法从NUMBERS
列(NUMBER_MONTH
列)和(NUMBER_FY
)中的字符串转换日期或时间。
有人可以看一下吗?基本上,我遇到的问题是我不能SHIP_DATE_MONTH
减去NUMBER_MONTH
和SHIP_DATE_FY
减去NUMBER_FY
。
列NUMBERS
为varchar
。格式为SSSYYMMFFFFFF
,其中
SSS
是商店电台,YY
是会计年度,MM
是月份,FFFFFF
是频率列SHIP_DATES
为datetime
。
列ID
是int。
这是我的代码:
CREATE TABLE #TEMP
(
NUMBERS VARCHAR (20),
SHIP_DATES DATETIME,
ID INT
)
INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '6/5/2010' , '123' )
INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '7/15/2013' , '123' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '9/8/2008' , '124' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '1/31/2013' , '124' )
SELECT SUBSTRING(NUMBERS, 6, 2) AS NUMBER_MONTH,
SUBSTRING(NUMBERS, 4, 2) AS NUMBER_FY,
DATEPART (MONTH, SHIP_DATES) AS SHIP_DATE_MONTH,
DATEPART (YEAR, SHIP_DATES) AS SHIP_DATE_FY,
ID
INTO #TEMP1
FROM #TEMP
--calculate the difference in month and fiscal year
SELECT DATEDIFF( YEAR , NUMBER_FY , SHIP_DATE_FY ) AS DIFF_YEAR ,
DATEDIFF( MONTH , NUMBER_MONTH , SHIP_DATE_MONTH ) AS DIFF_MONTH ,
ID
FROM #TEMP1
这是我收到的错误消息:
Conversion failed when converting date and/or time from character string.
请注意,这是转换为日期时间的方法,但我还没弄清楚如何让它工作:
CONVERT(VARCHAR , SHIP_DATES , 101 ) AS 'MM/DD/YYYY'
答案 0 :(得分:1)
当你调用DATEDIFF时,第二个和第三个参数的类型为DateTime,你传递第二个参数的字符串和第三个参数的整数。
我认为(如果我理解你要做什么)你应该将字符串转换为数字,摆脱DATEDIFF
并进行常规的减号操作。
评论后补充:
要将nvarcahr
强制转换为int,您可以像这样更改代码:
SELECT
CAST(SUBSTRING(NUMBERS, 6, 2) AS BIGINT) AS NUMBER_MONTH,
CAST(SUBSTRING(NUMBERS, 4, 2) AS BIGINT) AS NUMBER_FY,
DATEPART (MONTH, SHIP_DATES) AS SHIP_DATE_MONTH,
DATEPART (YEAR, SHIP_DATES) AS SHIP_DATE_FY,
ID
INTO #TEMP1
FROM #TEMP
答案 1 :(得分:0)
我会在这些方面尝试更多的东西:
CREATE TABLE #TEMP
(NUMBERS VARCHAR (20), SHIP_DATES_A DATETIME, SHIP_DATES_B DATETIME, ID INT)
然后进行测试:
INSERT INTO TEMP VALUES ('ABC1006000046', '6/5/2010','7/15/2013', '123')
INSERT INTO TEMP VALUES ('CDS0809000059', '9/8/2008','1/31/2013', '124')
然后这个查询:
select NUMBERS,SHIP_DATES_A,SHIP_DATES_B,ID,
DATEDIFF(month,ship_dates_a,ship_dates_b)
from temp
答案 2 :(得分:0)
为什么不这样做?
CREATE TABLE #TEMP
(
NUMBERS VARCHAR (20),
SHIP_DATES DATETIME,
ID INT
)
INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '6/5/2010' , '123' )
INSERT INTO #TEMP VALUES ( 'ABC1006000046' , '7/15/2013' , '123' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '9/8/2008' , '124' )
INSERT INTO #TEMP VALUES ( 'CDS0809000059' , '1/31/2013' , '124' )
SELECT CAST('20' + SUBSTRING(NUMBERS, 6, 2) + '-' + SUBSTRING(NUMBERS, 4, 2) + '-01' AS DATE) AS NumsDate,
SHIP_DATES
INTO #TEMP2
FROM #TEMP
SELECT
DATEDIFF(M, NumsDate, SHIP_DATES) AS Diff_In_Months,
DATEDIFF(YEAR, NumsDate, SHIP_DATES) AS Diff_In_Years
FROM
#TEMP2