----------------------------------------------------------------
-- Author  :DBA_HuangZJ(發糞塗牆)
-- Date    :2014-07-17 16:40:46
-- Version:
--      Microsoft SQL Server 2012 - 11.0.5058.0 (X64) 
-- May 14 2014 18:34:29 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go 
create table [A]([date] varchar(7))
insert [A]
select '2014-04' union all
select '2014-05' union all
select '2014-06' union all
select '2014-07'
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go 
create table [B]([name] varchar(4),[date] varchar(7),[number] int)
insert [B]
select '小明','2014-04',5 union all
select '小明','2014-05',7 union all
select '小红','2014-06',4
--------------开始查询--------------------------declare @s nvarchar(4000)
set @s=''
Select     @s=@s+','+quotename([date])+'=max(case when [date]='+quotename(date,'''')+' then [number] else 0 end)'
from (select a.[date],b.NAME,ISNULL(b.number ,0)number
from [A] LEFT JOIN [b] ON a.[date]=b.[date]) a group by [date]
exec('select [name]'+@s+' from (select a.[date],b.NAME,ISNULL(b.number ,0)number
from [A] LEFT JOIN [b] ON a.[date]=b.[date]) a where [name] is not null  group by [name]')
----------------结果----------------------------
/* 
name 2014-04     2014-05     2014-06     2014-07
---- ----------- ----------- ----------- -----------
小红   0           0           4           0
小明   5           7           0           0
*/