0

我的任务是计算一NUMBERS列和一SHIP_DATES列的月份和财政年度的差异。在计算之前,我无法从 ( ) 和 ( )NUMBERS列中的字符串转换日期或时间。NUMBER_MONTHNUMBER_FY

有人可以看看吗?基本上,我遇到的问题是我不能接受SHIP_DATE_MONTH减号NUMBER_MONTHSHIP_DATE_FY减号NUMBER_FY

  • NUMBERSvarchar。它的格式为SSSYYMMFFFFFF,其中

    • SSS是商店站,
    • YY是会计年度,
    • MM是月份,并且
    • FFFFFF是频率
  • SHIP_DATESdatetime

  • 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'
4

3 回答 3

1

当您调用DATEDIFF时,第二个和第三个参数的类型为 DateTime,您可以在其中为第二个参数传递字符串,为第三个参数传递整数。

我认为(如果我了解您要做什么)您应该将字符串转换为数字,摆脱DATEDIFF并执行常规减法运算。

评论后添加:要将 anvarcahr转换为 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
于 2013-09-10T17:08:50.193 回答
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
于 2013-09-10T16:58:40.460 回答
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
于 2013-09-10T18:19:48.900 回答