日期:2014-05-18 浏览次数:20585 次
select '[>=90]'范围 , sum(case when 英语>=90 then 1 else 0 end)英语, sum(case when 数学>=90 then 1 else 0 end)数学, sum(case when 物理>=90 then 1 else 0 end)物理, sum(case when 化学>=90 then 1 else 0 end)化学, sum(case when VB>=90 then 1 else 0 end)VB from tb union all select '[80-90]'范围 , sum(case when 英语 between 80 and 90 then 1 else 0 end)英语, sum(case when 数学 between 80 and 90 then 1 else 0 end)数学, sum(case when 物理 between 80 and 90 then 1 else 0 end)物理, sum(case when 化学 between 80 and 90 then 1 else 0 end)化学, sum(case when VB between 80 and 90 then 1 else 0 end)VB from tb ....
------解决方案--------------------
CREATE TABLE tb(ID int,Num int) INSERT tb SELECT 1,2 UNION ALL ALL SELECT 6,2 UNION ALL SELECT 7,1 UNION ALL SELECT 8,5 UNION ALL SELECT 9,1 GO --查询的存储过程 CREATE PROC p_Qry @group VARCHAR(1000) AS SET NOCOUNT ON IF @group LIKE '%[^0-9,]%' BEGIN RAISERROR(N'"%s" 中包含非数字数据',1,16,@group) RETURN END --将字符串分拆为分组表 DECLARE @t TABLE(ID int IDENTITY,Groups varchar(10),a int,b int) DECLARE @i int,@pid varchar(10) SELECT @i=CHARINDEX(',',@group+',') ,@pid=LEFT(@group,@i-1) ,@group=STUFF(@group,1,@i,'')+',' ,@i=CHARINDEX(',',@group) INSERT @t SELECT 'ID<='+@pid,NULL,@pid WHILE @i>1 BEGIN INSERT @t SELECT @pid+'<ID<='+LEFT(@group,@i-1),@pid,LEFT(@group,@i-1) SELECT @pid=LEFT(@group,@i-1) ,@group=STUFF(@group,1,@i,'') ,@i=CHARINDEX(',',@group) END INSERT @t SELECT 'ID>'+@pid,@pid,NULL --根据分组表统计 SELECT b.Groups,Num=ISNULL(SUM(a.Num),0) FROM tb a RIGHT JOIN @t b ON (a.ID<=b.b OR b.b IS NULL) AND(a.ID>b.a OR b.a IS NULL) GROUP BY b.ID,b.Groups ORDER BY b.ID GO --调用存储过程进行查询 EXEC p_Qry '2,3,6' /*--测试结果 Groups Num ---------- ----------- ID<=2 5 2<ID<=3 2 3<ID<=6 16 ID>6 7 --*/
------解决方案--------------------
---------------------------------