34,590
社区成员
发帖
与我相关
我的任务
分享
--10月1日 2000
--10月3日 3000
--10月5日 1000
declare @StartMonth datetime,@EndMonth datetime
select @StartMonth='2012-10-01',@EndMonth='2012-11-01'
;with M
as
(
select
replace(replace(convert(varchar(5),@StartMonth+number,110),'-0','-'),'-','月')+'日' as mon
from master.dbo.spt_values as a
where type='P' and number>=0 and @StartMonth<@EndMonth-number
)
select
a.mon as [month],
ISNULL(b.TotalAmount,0) as TotalAmount
from M as a
left join UserTable as b on a.mon=b.[month]
if OBJECT_ID('test') is not null
drop table test
if OBJECT_ID('[tempdb]..[#test]') is not null
drop table [tempdb]..[#test]
go
create table test(t_date varchar(10),value int)
insert into test
select '10月1日', 2000 union all
select '10月3日', 3000 union all
select '10月5日', 1000
create table #test (t_date varchar(10),value int)
declare @int int
set @int=1
while @int<6
begin
insert into #test
select '10月'+cast(@int AS varchar)+'日',0
set @int=@int+1
end
insert into #test
select * from test
select t_date, sum(value) from
#test group by t_date
WITH huang AS (
SELECT '10月1日' dt, 2000 mn
UNION ALL
SELECT '10月3日', 3000
UNION ALL
SELECT '10月5日', 1000)
SELECT CASE WHEN dt IS NULL THEN '10月' +CONVERT(VARCHAR(2),id)+'日' ELSE dt END dt,ISNULL (mn,0)mn
FROM (SELECT ROW_NUMBER()OVER (ORDER BY number ) id FROM master.dbo.spt_values) b LEFT JOIN huang a
ON b.id=SUBSTRING(dt,PATINDEX('%月%',dt)+1,PATINDEX('%日%',dt)-PATINDEX('%月%',dt)-1)
WHERE b.id<=(SELECT MAX(SUBSTRING(dt,PATINDEX('%月%',dt)+1,PATINDEX('%日%',dt)-PATINDEX('%月%',dt)-1)) FROM huang)
/*
dt mn
-------- -----------
10月1日 2000
10月2日 0
10月3日 3000
10月4日 0
10月5日 1000
(5 行受影响)
*/