使用RANK OVER函数SQL的列名无效

时间:2016-09-21 20:34:30

标签: sql sql-server rank adventureworks

尝试创建一个包含按产品销售的总数量的表格,并选择按日期分割的第三个最高销售数量的产品。继续收到错误

  

列名无效

代表我RANK () OVER语句的别名:

select 
    RANK () OVER (PARTITION BY t3.orderdate order by t3.total_amt_ordered) as ranking,
    t3.productid, 
    t3.orderdate,
    t3.total_amt_ordered
from 
    (select 
         t2.productid,
         t1.orderdate,
         SUM(t2.orderqty) as total_amt_ordered 
     from
         saleslt.salesorderheader t1 
     inner join 
         saleslt.salesorderdetail t2 on t1.salesorderid = t2.salesorderid 
     group by 
         productid, orderdate) t3
where 
    ranking = 3; 

3 个答案:

答案 0 :(得分:2)

以下查询将返回在订单日期级别分区的所有产品ID以及排名为3的所有订单数量。

SELECT * FROM
     (
        select 
                DENSE_RANK () OVER (PARTITION BY t3.orderdate order by  
                t3.total_amt_ordered DESC ) as ranking,
                t3.productid, 
                t3.orderdate,
                t3.total_amt_ordered
          from ( 
                 select 
                         t2.productid,
                         t1.orderdate,
                         SUM(t2.orderqty) as total_amt_ordered 
                   from
                         saleslt.salesorderheader t1 
                     inner join
                         saleslt.salesorderdetail t2 
                     on t1.salesorderid=t2.salesorderid 
                   group by productid, orderdate) t3
      ) Z
where Z.ranking= 3; 

答案 1 :(得分:2)

在RANK之前评估WHERE,因此您无法在没有派生表/ CTE的情况下直接使用它,但它也会在SUM之后计算,从而导致此查询:

//.h
#ifndef _DEBUG
    CTestDocument* GetDocument( ) { return dynamic_cast< CTestDocument* >( CView::GetDocument( ) ); }
#else
    CTestDocument* GetDocument( );
#endif

//.cpp
#ifdef _DEBUG
CTestDocument* RaRichView::GetDocument( )
{
    assert( dynamic_cast< CTestDocument* >( CView::GetDocument( ) ) );
    return dynamic_cast< CTestDocument* >( CView::GetDocument( ) ); }
#endif

答案 2 :(得分:0)

您可以使用这种方式,您不能在where条件

中使用排名查询和相同
;WITH cte
AS (SELECT
    RANK() OVER (PARTITION BY t3.orderdate ORDER BY t3.total_amt_ordered) AS ranking,
    t3.productid,
    t3.orderdate,
    t3.total_amt_ordered
FROM (SELECT
    t2.productid,
    t1.orderdate,
    SUM(t2.orderqty) AS total_amt_ordered
FROM saleslt.salesorderheader t1
INNER JOIN saleslt.salesorderdetail t2
    ON t1.salesorderid = t2.salesorderid
GROUP BY    productid,
            orderdate) t3)
SELECT
    *
FROM cte
WHERE ranking = 3;