求储存过程,两个表组合统计
数据信息存储表【Infos】有字段如下ID【ID号】,UserID【发布人ID】,AddTime【发布日期】,SortID【信息类别ID】,Status【状态值有3个值:正常,审核,过期】
有演示数据如下:
ID UserID AddTime SortID Status1 1 2012-4-1 0:00:00 2 12 1 2012-4-1 0:00:00 1 23 1 2012-4-1 0:00:00 4 34 1 2012-4-2 0:00:00 5 35 1 2012-4-3 0:00:00 6 26 1 2012-4-3 0:00:00 1 17 1 2012-4-5 0:00:00 2 18 1 2012-4-5 0:00:00 3 29 1 2012-4-6 0:00:00 4 310 2 2012-4-1 0:00:00 2 1...
SortID SortName1 营销1组2 营销2组3 营销3组4 营销4组5 营销5组6 营销6组...
类别名称 总计数据数量 正常数据数量 审核中数据数量 过期数据数量营销1组 2 1 1 0营销2组 2 2 0 0营销3组 1 0 1 0营销4组 2 0 0 2营销5组 1 0 0 1营销6组 1 0 1 0
--> 测试数据:[tbl]if object_id('[tbl]') is not null drop table [tbl]create table [tbl]([ID] int,[UserID] int,[AddTime] datetime,[SortID] int,[Status] int)insert [tbl]select 1,1,'2012-4-1 0:00:00',2,1 union allselect 2,1,'2012-4-1 0:00:00',1,2 union allselect 3,1,'2012-4-1 0:00:00',4,3 union allselect 4,1,'2012-4-2 0:00:00',5,3 union allselect 5,1,'2012-4-3 0:00:00',6,2 union allselect 6,1,'2012-4-3 0:00:00',1,1 union allselect 7,1,'2012-4-5 0:00:00',2,1 union allselect 8,1,'2012-4-5 0:00:00',3,2 union allselect 9,1,'2012-4-6 0:00:00',4,3 union allselect 10,2,'2012-4-1 0:00:00',2,1--> 测试数据:[tt]if object_id('[tt]') is not null drop table [tt]create table [tt]([SortID] int,[SortName] varchar(7))insert [tt]select 1,'营销1组' union allselect 2,'营销2组' union allselect 3,'营销3组' union allselect 4,'营销4组' union allselect 5,'营销5组' union allselect 6,'营销6组'goif OBJECT_ID('pro_tracy')is not nulldrop proc pro_tracygocreate proc pro_tracy @UserID intascreate table #tbl([SortName] varchar(20),[UserID] int,[Status] int)insert #tblselect b.SortName,a.UserID,a.[Status] from tbl a full join tt b on a.SortID=b.SortIDwhere UserID=@UserID and [AddTime] between '2012-1-1' and '2012-4-30'select SortName as 类别名称 ,COUNT(*) as 总计数据数量,SUM(case when [Status]=1 then 1 else 0 end) as 正常数据数量,SUM(case when [Status]=2 then 1 else 0 end) as 审核中数据数量,SUM(case when [Status]=3 then 1 else 0 end) as 过期数据数量from #tbl group by SortNameexec pro_tracy 1/*类别名称 总计数据数量 正常数据数量 审核中数据数量 过期数据数量营销1组 2 1 1 0营销2组 2 2 0 0营销3组 1 0 1 0营销4组 2 0 0 2营销5组 1 0 0 1营销6组 1 0 1 0*/