需要将两个日期部分组合成一个新的日期字段而不添加结果

Need To combine two date parts into a new date field without the results adding

我正在尝试获取日期和年份这两个日期部分,以便在不添加结果的情况下合并到一个新的数据字段中。我不知道我做错了什么,任何帮助将不胜感激。

sELECT   Convert(varchar,dbo.tblRpt291_AgingSnapshot.ReportDate)as DATEINT, Datepart(DAY,dbo.tblRpt291_AgingSnapshot.ReportDate)+ ''+''+DATEPART(YEAR,dbo.tblRpt291_AgingSnapshot.ReportDate) as Date, dbo.tblRpt291_AgingSnapshot.ReportDate, First.Age AS AvgAge, First.CountOfCalls AS Inventory
FROM         dbo.tblRpt291_AgingSnapshot LEFT OUTER JOIN
                          (SELECT     ReportDate, AVG(CAST(Age AS Numeric)) AS Age, SUM(CAST(CountOfCalls AS Numeric)) AS CountOfCalls
FROM         dbo.tblRpt291_AgingSnapshot AS tblRpt291_AgingSnapshot_1
WHERE     (Client = 'PEMS') AND (WorkableStatus = 'Workable') AND (Worktype IN ('Individual PCP', 'Group PCP'))
GROUP BY ReportDate) AS First ON dbo.tblRpt291_AgingSnapshot.ReportDate = First.ReportDate
WHERE     (MONTH(dbo.tblRpt291_AgingSnapshot.ReportDate) = 12) AND (YEAR(dbo.tblRpt291_AgingSnapshot.ReportDate) in (2013,2014))
GROUP BY dbo.tblRpt291_AgingSnapshot.ReportDate, First.Age, First.CountOfCalls
order by dbo.tblRpt291_AgingSnapshot.ReportDate ​

您需要 CAST() 在连接之前将两个部分作为字符串,因此它们不会加在一起,因为 DATEPART() 返回一个整数:

, CAST(Datepart(DAY,dbo.tblRpt291_AgingSnapshot.ReportDate) AS VARCHAR(5))+CAST(DATEPART(YEAR,dbo.tblRpt291_AgingSnapshot.ReportDate) AS VARCHAR(5)) as Date

此外,table别名有助于提高可读性,我建议避免使用关键字作为别名:

SELECT   Convert(varchar,a.ReportDate)as DATEINT
       , CAST(Datepart(DAY,a.ReportDate) AS VARCHAR(5))+CAST(DATEPART(YEAR,a.ReportDate) AS VARCHAR(5)) as Dt
       , a.ReportDate
       , b.Age AS AvgAge
       , b.CountOfCalls AS Inventory
FROM         dbo.tblRpt291_AgingSnapshot a 
LEFT OUTER JOIN     (SELECT     ReportDate, AVG(CAST(Age AS Numeric)) AS Age, SUM(CAST(CountOfCalls AS Numeric)) AS CountOfCalls
                     FROM         dbo.tblRpt291_AgingSnapshot AS tblRpt291_AgingSnapshot_1
                     WHERE     (Client = 'PEMS') AND (WorkableStatus = 'Workable') AND (Worktype IN ('Individual PCP', 'Group PCP'))
                     GROUP BY ReportDate) AS b
    ON a.ReportDate = b.ReportDate
WHERE     (MONTH(a.ReportDate) = 12) AND (YEAR(a.ReportDate) in (2013,2014))
GROUP BY a.ReportDate, b.Age, b.CountOfCalls
order by a.ReportDate ​

您需要转换日期部分 - SQL 将它们视为整数,您希望它们表现得像文本。

举个例子:

select cast(Datepart(DAY,getdate()) AS varchar(2)) + 

cast(DATEPART(YEAR,getdate()) AS varchar(4)) as Date

将 getdate() 替换为您的列名称。