使用聚合函数时,CTE的行为异常

时间:2018-11-22 15:45:26

标签: sql sql-server sql-server-2008 sql-server-2012

当我在CTE中使用聚合函数时,收到一条错误消息。下面是查询和与之关联的错误消息。当我删除聚合函数时,它工作正常。在某个地方,我错过了窍门。

代码:

<div id="main">
  <div class="container">
    <div id="box1">box1</div>
  </div>
  <div class="container">          
    <div id="box2">box2</div>
  </div>
</div>

错误消息:

  

在选择列表中,列; With CTE as ( Select sn, ed, sum(c) c, row_number() over (partition by sn, ed order by sn, sum(c) desc, ed) rn from TD where ed >= '11/15/2018' ) select * from CTE 无效,因为它没有包含在聚合函数或group by子句中。

1 个答案:

答案 0 :(得分:2)

您在查询中使用了汇总功能,但未使用分组依据

With CTE as (
    Select
        sn,
        ed,
        sum(c) c,
        row_number() over (partition by sn order by  sum(c) desc) rn
    from TD
    where ed >= '11/15/2018'
   group by sn,
        ed
)
select * from CTE where rn<=3