错误:窗口函数只能出现在SELECT或ORDER BY子句中。在子选择上

时间:2016-09-13 19:02:46

标签: sql sql-server subquery

我试图在子查询中使用行号来从我的存储过程的另一个表部分带来值如下所示。子查询出错:

;with cte as
(
    select 
        @sDate StartDate, 
        DATEADD(wk,DATEDIFF(wk, 0, @sDate),7) EndDate  

    union all

    select  
        dateadd(d, 1, EndDate),
        dateadd(ww, 1, dateadd(ww, 1, StartDate)) 
    from 
        cte
    where 
        dateadd(wk, 1, StartDate) <=  @eDate
), cte2 as 
(
    select 
        *, 
        (ROW_NUMBER() OVER(ORDER by iD)) as rn 
    from 
        [KFC].[dbo].[tblCOMPANYTAXPERIOD] 
    where 
        [COMPANYTAXYEARID] = 4 
)
select  
    REPLICATE('0', 3 - LEN(RTRIM(ROW_NUMBER() OVER(ORDER by EndDate)))) + RTRIM(ROW_NUMBER() OVER(ORDER by EndDate)) AS [PAYROLLRUNNUMBER],
    (CONVERT(VARCHAR(11), StartDate, 106)) as PERIODSTARTDATE,    
    (CONVERT(VARCHAR(11), EndDate, 106)) as PERIODENDDATE, 
    (select iD 
     from cte2 
     where [COMPANYTAXYEARID] = 4 
       and [TAXPERIODNO] = rn) AS [COMPANYTAXPERIODID]  
from 
    cte c

错误:

  

子查询返回的值超过1。当子查询遵循=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询用作表达式时,不允许这样做。

1 个答案:

答案 0 :(得分:0)

你可以使用cte,尝试这样的事情:where子句

中不允许使用窗口函数
;with cte as
(
  select @sDate StartDate, DATEADD(wk,DATEDIFF(wk, 0, @sDate),7) EndDate --, ROW_NUMBER() OVER(ORDER by @sDate) as  number
  union all
  select  dateadd(d, 1, EndDate),
    dateadd(ww, 1, dateadd(ww, 1, StartDate))--,ROW_NUMBER() OVER(ORDER by EndDate) as  number
  from cte
  where dateadd(wk, 1, StartDate)<=  @eDate
), cte2 as 
( select iD, [TAXPERIODNO], (ROW_NUMBER() OVER(ORDER by EndDate)) as rn from [KFC].[dbo].[tblCOMPANYTAXPERIOD] where [COMPANYTAXYEARID] = 4 )
--Insert Into #Temp select * from cte 
select  REPLICATE('0',3-LEN(RTRIM( ROW_NUMBER() OVER(ORDER by EndDate)))) + RTRIM(ROW_NUMBER() OVER(ORDER by EndDate)) as [PAYROLLRUNNUMBER]
,  (CONVERT(VARCHAR(11),StartDate,106)) as PERIODSTARTDATE, (CONVERT(VARCHAR(11),EndDate,106)) as PERIODENDDATE  
,   (select iD from cte2 where  [TAXPERIODNO] =rn )as  [COMPANYTAXPERIODID]  from cte c