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

语法问题
declare @sql varchar(8000) 
set @sql='select plevel'
select @sql=@sql+',['+dd+']=sum(case convert(varchar(10),workdate,120) when '''+dd+''' then Times*qty else 0 end)'
from (select distinct dd=convert(varchar(10),workdate,120) from tb) ss
set @sql=@sql+' from tb group by plevel'
exec(@sql)
我把上面的换成了下面的:
declare @sql varchar(8000)
set @sql='select plevel'
select @sql=@sql+',['+dd+']=sum(case convert(varchar(10),workdate,120) when '''+dd+''' then Times*qty else 0 end)'
from (select distinct dd=convert(varchar(10),workdate,120) from (Select a.* from(Select plevel,workdate,qty*times as ff from tb group by plevel,workdate,qty*times ) a where ff>500)) ss
set @sql=@sql+' from tb group by plevel'
exec(@sql)
就提示Incorrect syntax near ')'
我就是把倒数第三行的表tb换成了(Select a.* from(Select plevel,workdate,qty*times as ff from tb group by plevel,workdate,qty*times ) a where ff>500),这句语句执行没有问题的。为什么放在这里就出错了?
请高手帮忙!谢谢!

------解决方案--------------------
SQL code

declare @sql varchar(8000)
set @sql='select plevel'
select 
    @sql=@sql+
        ',['+dd+']=sum(
                        case convert(varchar(10),workdate,120) 
                            when '''+dd+''' 
                            then Times*qty 
                            else 0 
                        end
                        )'
from (
    select distinct 
        dd=convert(varchar(10),workdate,120) 
        from (
                Select 
                    a.* 
                from
                (
                    Select 
                        plevel,
                        workdate,
                        qty*times as ff 
                    from tb 
                    group by plevel,workdate,qty*times 
                ) a 
              )tmp
        where ff>500
      
    ) ss
set @sql=@sql+' from tb group by plevel'
exec(@sql)

------解决方案--------------------
SQL code

declare @sql varchar(8000)
set @sql='select plevel'
select @sql=@sql+',['+dd+']=sum(case convert(varchar(10),workdate,120) when '''+dd+''' then Times*qty else 0 end)'
from 
(
    select distinct dd=convert(varchar(10),workdate,120) 
    from 
    (
        Select a.* 
        from
        (
            Select plevel,workdate,qty*times as ff 
            from tb 
            group by plevel,workdate,qty*times 
        ) a 
        where ff>500
    ) ss) aa
set @sql=@sql+' from tb group by plevel'