日期:2014-05-18  浏览次数:20743 次

SQL存储过程行转列 有空值怎么处理
CJ表
张三 语文 80
张三 数学 100
张三 物理 79
JIM 物理 100
MACK DJ 100
MACK NULL NULL

存储过程
SQL code

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[pro_ROWTOCOL] 
    -- Add the parameters for the stored procedure here
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    declare @sql varchar(4000)
    set @sql = 'select Name'
    select @sql = @sql + ',isnull(sum(case Subject when '''+Subject+''' then Result end),0) ['+Subject+']'
    from (select distinct Subject from CJ) as a
    select @sql = @sql+' from cj group by name'
    exec(@sql)

END



------解决方案--------------------
这个有点困难
------解决方案--------------------
你还没说你的问题出在哪儿?。。。
------解决方案--------------------
select distinct Subject from CJ where subject is not null
------解决方案--------------------
MACK NULL NULL 
既然连课程都没有还有统计的价值吗?

直接 where 课程 is not null
------解决方案--------------------
case when 字段 is null then '未定义' else 字段 end
------解决方案--------------------
sum(case Subject when '''+Subject+''' then Result end),0) ['+Subject+']

=>

max(case when Subject='''+Subject+''' then Result when Subject isnull then '未定义' end) as ['+Subject+']'
------解决方案--------------------
你可以用代码直接得到结果循环插入不就行了吗,非得用存储过程吗,不是都是以解决问题为主吗

你可以试试呀


------解决方案--------------------
isnull(字段,0)
------解决方案--------------------

------解决方案--------------------
这个有点困难