日期:2014-05-17 浏览次数:20575 次
WITH CTE (Area,YearMonth,Type1,Type2,Type3)
AS (
SELECT N'长沙市', '200608',null,null,2 UNION ALL
SELECT N'上海', '200608',1, 7,10 UNION ALL
SELECT N'北京', '200608',1,null,null UNION ALL
SELECT N'广州', '200608',null,null,2 UNION ALL
SELECT N'长沙市', '200609',null,null,1 UNION ALL
SELECT N'上海', '200609',null,null,8 UNION ALL
SELECT N'北京', '200609',null, 1,15 UNION ALL
SELECT N'广州', '200609',1,null,null UNION ALL
SELECT N'上海', '200610',null,null,1 UNION ALL
SELECT N'广州', '200610',null,null,null UNION ALL
SELECT N'长沙市', '200611',null,null,null UNION ALL
SELECT N'广州', '200612',1,null,4
),
t
as
(
select a.area,
b.yearmonth
from (select distinct area from cte) a
cross join (select distinct yearmonth from cte)b
)
SELECT t.Area
,SUBSTRING(t.YearMonth,1,4) [YEAR],
SUBSTRING(t.YearMonth,5,2)[month],
t.yearmonth
,ISNULL(SUM(c.Type1),0) AS Type1
,ISNULL(SUM(c.Type2),0) AS Type2
,ISNULL(SUM(c.Type3),0) AS Type3
FROM t
left join CTE c
on t.area = c.area