此子查询出错

时间:2015-12-14 15:37:01

标签: sql sql-server-2005 subquery

此查询:

left join (select tSpent, Customerid
from   (select SUM(spent) as tSpent, Customerid,
        RN = ROW_NUMBER() OVER (PARTITION BY Customerid ORDER BY Customerid DESC)
        from   Customer_Sales
        WHERE Customerid is not null)
              where   RN = 1) Sales ON Customer_Sales.Customerid = Data.Customerid

RN=1行上给我一个错误:

  

关键字'where'

附近的语法不正确

2 个答案:

答案 0 :(得分:5)

(select tSpent, Customerid
 from (select SUM(spent) as tSpent, Customerid,
        RN = ROW_NUMBER() OVER (PARTITION BY Customerid ORDER BY Customerid DESC)
        from   Customer_Sales
        WHERE Customerid is not null) t --use a alias for the derived table
 where RN = 1) Sales ON Customer_Sales.Customerid = Data.Customerid

不确定为何使用row_number。您还应该group by customerid

内部查询可以简化为

select SUM(spent) as tSpent, Customerid
from  Customer_Sales
WHERE Customerid is not null
group by customerid

因为您只是想要获得每个客户的总支出。

答案 1 :(得分:1)

ROW_NUMBER()函数是在SQL Server 2005中引入的。因此您将无法使用它。您也错过了vkp指出的子查询的别名,并且您无法在SELECT子句中使用您在WHERE中分配的别名(过滤在select之前发生,本质上)。 / p>