日期:2014-05-18 浏览次数:20619 次
create table T(ID int identity(1,1),lie1 int,lie2 int,lie3 int) insert into T select 2,1,0 union all select 0,1,1 union all select 0,2,1 union all select 1,1,2 union all select 0,0,1 union all select 1,2,2 declare @s1 nvarchar(4000); declare @s2 nvarchar(4000); declare @s3 nvarchar(4000); set @s1='标题=''lie1''' set @s2='''lie2''' set @s3='''lie3''' Select @s1=@s1+','+quotename(lie1)+'=sum(case when [lie1]='+quotename([lie1],'''')+' then 1 else 0 end)' from T group by [lie1] Select @s2=@s2+','+'sum(case when [lie2]='+quotename([lie2],'''')+' then 1 else 0 end)' from T group by [lie2] Select @s3=@s3+','+'sum(case when [lie3]='+quotename([lie3],'''')+' then 1 else 0 end)' from T group by [lie3] exec('select '+@s1+' from T union all select '+@s2+' from T union all select'+@s3+' from T') drop table T /* 标题 0 1 2 ---- ----------- ----------- ----------- lie1 3 2 1 lie2 1 3 2 lie3 1 3 2 */
------解决方案--------------------
CASE 计算条件列表并返回多个可能结果表达式之一。 CASE 具有两种格式: 简单 CASE 函数将某个表达式与一组简单表达式进行比较以确定结果。 CASE 搜索函数计算一组布尔表达式以确定结果。 两种格式都支持可选的 ELSE 参数。 语法 简单 CASE 函数: CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression END
------解决方案--------------------
create table T(ID int identity(1,1),lie1 int,lie2 int,lie3 int) insert into T select 2,1,0 union all select 0,1,1 union all select 0,2,1 union all select 1,1,2 union all select 0,0,1 union all select 1,2,2 --SELECT * FROM T SELECT LIE='LIE1' , SUM(CASE WHEN LIE1=0 THEN 1 ELSE 0 END)AS '0', SUM(CASE WHEN LIE1=1 THEN 1 ELSE 0 END)AS '1', SUM(CASE WHEN LIE1=2 THEN 1 ELSE 0 END)AS '2' FROM T UNION ALL SELECT LIE='LIE2' , SUM(CASE WHEN LIE2=0 THEN 1 ELSE 0 END)AS '0', SUM(CASE WHEN LIE2=1 THEN 1 ELSE 0 END)AS '1', SUM(CASE WHEN LIE2=2 THEN 1 ELSE 0 END)AS '2' FROM T UNION ALL SELECT LIE='LIE3'