2016-09-21 78 views
1

試圖創建一個表格,其中包含按產品銷售的總數量,並選擇按日期分段的第三個銷售數量最高的產品。一直得到錯誤帶RANK OVER函數的列名稱無效SQL

無效列名

的別名我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; 
+0

您的期望是什麼? – Teja

回答

1

下面的查詢將返回所有在訂單日期水平劃分的產品ID和所有的訂單數量排在三位。

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; 
+0

謝謝!現在在where語句上出現錯誤。我能不包括它嗎? –

+0

你有什麼錯誤?還有,我的查詢沒有where子句嗎?如果是這樣,輸出中的最後一列是什麼? – Teja

+0

沒有where子句,它不起作用。顯示:Msg 102,Level 15,State 1,Line 48 ';'附近的語法不正確。 –

0

您可以用這種方式,你不能用排名查詢,同在那裏的條件

;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; 
+0

這給出了所有的空值。 –

1

WHERE排名前計算,所以你不能沒有派生表/ CTE直接使用它,但它也是在SUM之後計算的,導致在此查詢中:

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

這給了我空位。 –

+0

@CameronWarren:NULLs?你可能需要切換到'DENSE_RANK'(或者可能是'ROW_NUMBER') – dnoeth