日期:2014-05-16  浏览次数:20386 次

求一条SQL语句!!!帮忙看下需求
   数据库里面有好多条数据,我想通过一个时间字段(时间字段是字符串存储)来统计数据


   比如:
   2014-10-1 ,2014-8-6,2013-8-6,2014-10-2

我想统计成
         2014-10
        2014-8
       2013-8
     

这样子,其实就是把相同的月份来统一一起!!
------解决方案--------------------
可以这样:

select convert(varchar(7),GETDATE(),120)
/*
2014-03
*/

select convert(varchar(7),时间字段,120)
from 表
group by convert(varchar(7),时间字段,120)

------解决方案--------------------
declare @str varchar(8000) 

set @str = '2014-10-1,2014-8-6,2013-8-6,2014-10-2' 

set @str =  'select  dt='''+replace(@str,',',''''+' union all select ''')+'''' 


set @str='select distinct convert(varchar(7),cast(dt as datetime),120) as dt  from ('+@str+') a'

EXEC(@str)

/*dt
-------
2013-08
2014-08
2014-10

(3 行受影响)
*/




------解决方案--------------------

create table ho(col varchar(20))

insert into ho(col)
 select '2014-10-1' union all
 select '2014-8-6' union all
 select '2013-8-6' union all
 select '2014-10-2'


select distinct left(convert(varchar,cast(col as datetime),23),7) 'col'
 from ho

/*
col
--------------
2013-08
2014-08
2014-10

(3 row(s) affected)
*/