select STime,SDyp=(
select sum(SDyp) from(
select top 120 SDyp from (SELECT sum(SDyp) as SDyp,STime FROM @REC GROUP BY STime) X 
where  X.STime>=a.STime
)aa having count(*)=120)
from (SELECT sum(SDyp) as SDyp,STime as STime FROM @REC GROUP BY STime) a--->這一行有問題,裡面不是有個變量嗎?

解决方案 »

  1.   

    子查询的字段不能那样引用,用中间表过度一下:
    SELECT sum(SDyp) as SDyp,STime as STime into #t FROM @REC GROUP BY STime
    select STime,SDyp=(
    select sum(SDyp) from(
    select top 120 SDyp from #t X 
    where  X.STime>=a.STime
    )aa having count(*)=120)
    from #t a
    drop table #t
      

  2.   

    select STime,SDyp=(
    select sum(SDyp) from(
    select top 120 SDyp from (SELECT sum(SDyp) as SDyp,STime FROM @REC GROUP BY STime) X 
    where  X.STime>=a.STime  ---*** 这里嵌套得太深,取不到a.STime 
    )aa having count(*)=120)
    from (SELECT sum(SDyp) as SDyp,STime as STime FROM @REC GROUP BY STime) a
      

  3.   

    --用中间表(如 pbsql(风云) 的)--按楼主的语句分析,直接这样写也可以:
    select STime,SDyp=(
    select sum(SDyp) from(
    select top 120 SDyp 
    from (
    SELECT sum(SDyp) as SDyp,STime 
    FROM @REC 
    GROUP BY STime
    ) X where  X.STime>=a.STime
    )aa having count(*)=120)
    from @REC a
    GROUP BY STime