以YYYYMMDD SQL格式将DATETIME转换为8位INT

时间:2017-07-25 19:28:25

标签: sql sql-server datetime int

需要加入两个表格。一个表有一个'datekey'列,它是来自dimdate表的格式为YYYYMMDD的int,另一个表有一个'CreatedOn'列,它是一个日期时间。我最初将日期时间转换为日期,因为这是group by似乎正常工作的唯一方式。我一直收到错误“操作数类型冲突:日期与int不兼容”,因为“on d.datekey = BBB.datekey”行...对一个简单的解决方法的任何建议?

select 
    distinct CONVERT (date,convert(char(8),d.datekey )) as Date
    , isnull(BBB.reccount,0) DimAccount
from dimdate d
left outer join(
    Select 
        cast(createdon as date) datekey
        , count(*) RecCount
    from DimAccount 
    group by cast(createdon as date)
)BBB on d.datekey = BBB.datekey
where d.datekey like '2017%'
group by d.datekey
,BBB.RecCount
having MAX(DATEDIFF(dd, CONVERT(date, CAST(d.Datekey  AS CHAR(8)), 101), GETDATE())) > -1
order by date desc

1 个答案:

答案 0 :(得分:2)

这样的事情应该让你开始

from dimDate dd join dimAccount da 
on cast(da.createdOn as date) = cast(cast(dd.dateKey as char(8)) as date)

where dd.year = 2017  -- or you can filter on da.createdOn >= '20170101'

实际上,如果您的dimDate表具有实际日期列,则根本不必转换dateKey。