如何使用年月列计算年龄?

时间:2016-06-28 20:35:58

标签: sql-server

我尝试使用YRMO (Year/Month Ex:201606)列来获取产品的年龄。我希望能够拥有产品,Yrmo和年龄:

 Product  | YrMo   | Age|
 A        | 201602 |  1 |
 A        | 201603 |  2 |
 B        | 201605 |  4 |

我使用此方法但无法获得结果

 SELECT 
       Product      
     , YrMo
     , [Month_#]    =   DATEDIFF(MONTH,201601,YrMo) 

 FROM Table

当我使用日期类型时,它连续几个月返回:

  [Month_#] =   DATEDIFF(MONTH,'1900-01-01',YrMo)   

相反..有关如何解决这个问题的任何提示吗?

4 个答案:

答案 0 :(得分:1)

简单

SELECT  Product,
        YrMo,
        DATEDIFF(month,STUFF(YrMo,5,0,'-')+'-01','2016-01-01') as Age
FROM YourTable

输出:

Product YrMo    Age
A       201602  1
A       201603  2
B       201605  4

答案 1 :(得分:1)

SELECT product, 
       yrmo, 
       [Month_#] = Datediff(month, Cast('1900-01-01' AS DATE), Cast( 
                   '20160101' AS DATE) 
                   ) 
FROM   table 

答案 2 :(得分:1)

您接近查询,但不能只将int或6位数字符串转换为日期。这是您的查询,已修改:

select 
    Product      
    , YrMo
    , [Month_#] = datediff(month, cast(cast(201601 as varchar(11)) + '01' as date), cast(cast(YrMo as varchar(11)) + '01' as date))
from Products

结果:

Product  YrMo    Month_#
A        201602  1
A        201603  2
B        201605  4

请注意,我正在为varchar注入内容,然后附加'01'以使其成为完整日期。根据您实际使用的数据类型,您可以使它更漂亮。

答案 3 :(得分:1)

DECLARE @T TABLE (Product VARCHAR(1), YrMo INT,  Age INT)
INSERT INTO @T VALUES
( 'A',         201602 ,  1) ,
( 'A' ,        201603 ,  2),
( 'B'  ,       201605 ,  4)


    SELECT      AGE, YRMO, 
                (YRMO / 100 * 12 +  YRMO % 100 ) - (201601 /100 *12 + 201601 % 100) AS  AGE
    FROM    @T