34,836
社区成员




--創建數據
create table #tb(年 int, 月 int, 销售 varchar(10), 业绩 int)
insert into #tb
select 2013 , 5 , '张三' , 1000
UNION ALL
select 2013 , 6 , '张三' , 2000
--查詢
SELECT b.年,b.月,b.销售,ISNULL(c.业绩,0) 业绩
FROM
(
SELECT a.年,t.number 月,a.销售
FROM (SELECT DISTINCT 年,销售 FROM #tb) a,master..spt_values t
WHERE t.type = 'P' and t.number >= 1 and t.number <=12
) b
LEFT JOIN #tb c ON b.年=c.年 AND b.月=c.月 AND b.销售=c.销售
with a(a,b,c,d)as(
select 2013,5,'a',1000)
select a,case when b=number then b else number end,
c,case when b=number then d else 0 end
from a
left join(select distinct number from master..spt_values
where number between 1 and 12)b
on 1=1
--drop table tb
create table tb(年 int, 月 int, 销售 varchar(10), 业绩 int)
insert into tb
select 2013 , 5 , '张三' , '1000'
select tt.年,t.number as 月,tt.销售,ISNULL(tb.业绩,0) as 业绩
from
(
select 年,销售 from tb
)tt
inner join master..spt_values t
on t.type = 'P' and t.number >= 1 and t.number <=12
left join tb
on tb.年 = tt.年
and tb.销售 = tt.销售
and tb.月 = t.number
/*
年 月 销售 业绩
2013 1 张三 0
2013 2 张三 0
2013 3 张三 0
2013 4 张三 0
2013 5 张三 1000
2013 6 张三 0
2013 7 张三 0
2013 8 张三 0
2013 9 张三 0
2013 10 张三 0
2013 11 张三 0
2013 12 张三 0
*/