0

我在一个消耗大量 RAM 的较大查询中有这一部分:

TopPerPost as
(
   select Id,
      CloseReasonTypeId,
      Name,
      ReasonsPerPost.TotalByCloseReason,
      row_number() over(partition by Id order by TotalByCloseReason desc) seq -- Get the most common Id (The most common close Reason)
   from ReasonsPerPost
   where Name is NOT NULL and TopPerPost.seq=1 -- Remove useless results here, instead of doing it later
)

但我得到了无法绑定多部分标识符“TopPerPost.seq”。
最后一个细节......我只使用该表Name后面INNER JOIN的列。

4

2 回答 2

1

您不能在同一查询的 where 中引用窗口函数。只需创建第二个 cte。

with TopPerPost as
(
   select Id,
      CloseReasonTypeId,
      Name,
      ReasonsPerPost.TotalByCloseReason,
      row_number() over(partition by Id order by TotalByCloseReason desc) seq -- Get the most common Id
   from ReasonsPerPost
   where Name is NOT NULL 
)
, OnlyTheTop as
(
    select *
    from TopPerPost
    where seq = 1
)

或者你可以这样做。

select * from 
(
   select Id,
      CloseReasonTypeId,
      Name,
      ReasonsPerPost.TotalByCloseReason,
      row_number() over(partition by Id order by TotalByCloseReason desc) seq -- Get the most common Id
   from ReasonsPerPost
   where Name is NOT NULL 
) s
where seq = 1

这是另一个选项,应该消除返回这么多行的需要。

select Id,
      CloseReasonTypeId,
      Name,
      s.TotalByCloseReason
   from ReasonsPerPost rpp
   cross apply
   (
        select top 1 TotalByCloseReason
        from ReasonsPerPost rpp2
        where rpp2.Id = rpp.Id
        order by TotalByCloseReason desc
   ) s
   where Name is NOT NULL 

尝试#4 ...使用 sql fiddle 会容易得多。

select Id,
      CloseReasonTypeId,
      Name,
      s.TotalByCloseReason
   from ReasonsPerPost rpp
   inner join
   (
        select top 1 TotalByCloseReason
        from ReasonsPerPost rpp2
        where rpp2.Id = rpp.Id
        and Name is NOT NULL
        order by TotalByCloseReason desc
   ) s on s.Id = rpp.Id
   where Name is NOT NULL
于 2014-07-30T21:36:10.987 回答
0

以下可能满足您的需要。但如果不看数据,很难判断它是否会。

;with t as
(
  Select Id, max(totalbyclosereason) TC from reasonsperpost where name is not null group by id
)
Select T.id,t.tc,c.closereasontypeid,c.name 
From t join reasonsperpost c on t.id = c.id and t.tc = c.totalbyclosereason
于 2014-07-30T21:59:37.377 回答