请教一个问题

swblood 2012-11-13 08:23:41
现在有一个表 按日期汇总了一些数据 但是日期是不连续的 怎样查询 能得到一个日期连续的表呢?
比如 表里 有数据
10月1日 2000
10月3日 3000
10月5日 1000

想查询得到的结果是

10月1日 2000
10月2日 0
10月3日 3000
10月4日 0
10月5日 1000
...全文
104 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
中国风 2012-11-15
  • 打赏
  • 举报
回复
usertable--用户表改改表名和列名,测测
中国风 2012-11-15
  • 打赏
  • 举报
回复
--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]
坚_持 2012-11-15
  • 打赏
  • 举报
回复
习惯性蹭分 2012-11-14
  • 打赏
  • 举报
回复
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
發糞塗牆 2012-11-13
  • 打赏
  • 举报
回复
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 行受影响)
 */

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧