2012-03-22 31 views
1

日期在我SQL Server数据库的字符串我曾经日期存储为CHAR(12)按以下格式提取一个月:如何从代表TSQL

为yyyymmddhhmm

我没有创建定义,我不能修改它。我总是通过使用C#在应用程序级别处理这个字符串。

现在我需要在TSQL执行任务,我需要组按月。因此我需要提取月份。是否有任何TSQL功能可用于此任务?

如果没有,它是一个很好的解决方案,以创建一个存储过程,getMonth(stringDate),是以串并提取第四和第五个字符的呢?我可以使用该条款:

group by getMonth(stringDate) 

在我的查询?谢谢

+0

您确定要按月分组而不是按月分组吗?你真的想结合不同年份同月的价值吗? – GilM 2012-03-22 19:12:24

回答

1

可以使用下面是获取你的月份,因为月份在4个字符年后总是2个字符。

declare @date char(12) 
set @date = '201203220906' 
select substring(@date, 5, 2) 

结果:03

或另一种方式来得到它,那么你可以group by在任一查询的结果:

declare @date char(12) 
set @date = '201203220906' 
select Month(cast(left(@date, 8) as datetime)) 
3

你可以;

SUBSTRING(fld, 5, 2) 

个人而言,我不会创造这么简单的东西(这是你会考虑什么,而不是SP),除非你发现自己需要该字符串转换为UDF DATETIME小号

1

假设

CREATE TABLE #Table(
    DateValue char(12), 
    Value int) 

INSERT INTO #Table VALUES ('20120110833', 1) 
INSERT INTO #Table VALUES ('20120110833', 2) 
INSERT INTO #Table VALUES ('20120110833', 3) 
INSERT INTO #Table VALUES ('20120210833', 4) 
INSERT INTO #Table VALUES ('20120210833', 5) 

你可以简单地这样做:

select 
    MONTH(CAST(LEFT(DateValue, 8) as datetime)) Month, 
    SUM(value) 
FROM 
    #Table 
GROUP BY 
    MONTH(CAST(LEFT(DateValue, 8) as datetime)) 

修剪时/分的一部分,强制转换为datetime和应用MONTH函数

0

对于这个特定的情况下(char类型与格式为yyyymmddhhmm日期),你可以在查询中使用的下一个功能:

子(提取年月日), 转换(得到datetime值), 日期部分(取得月份部分)

...那么你可以通过组每月(或其他日期部分),改变datecolumnname和表名与适当的价值

select datepart(month,convert(datetime,substring(datecolumnname,1,8),112)), 
    count(datepart(month,convert(datetime,substring(datecolumnname,1,8),112))) 
from tablename 
    group by datepart(month,convert(datetime,substring(datecolumnname,1,8),112))