SQL Server:错误MSG 102和MSG 156

时间:2016-04-09 16:07:25

标签: sql sql-server

请帮帮我。我写了查询

 <body ng-app="Mymodule">

我收到了以下消息

  

Msg 102,Level 15,State 1,Line 13
  ')'附近的语法不正确。

     

Msg 156,Level 15,State 1,Line 18
  关键字“group”附近的语法不正确。

有人可以请告诉我如何解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

SQL Server 2014支持FIRST / LAST_VALUE

with cte as 
  (   
      select *,
           product, 
           price as first_price, 
           row_number() over (partition by product order by date) as rownumber,
           last_value(price) -- price of the row with the latest date
           over (partition by product 
                 order by date rows
                 rows between unbounded preceding and unbounded following) as last_price
           count(*) over (partition by product) as maxrn
      from saleslist sl
      where datediff( month, date, getdate() ) < 2 
   )
select product, 
       (last_price - first_price) / first_price
from cte
where rownumber = 1;

答案 1 :(得分:0)

您需要子查询的表别名。但是,您的查询过于复杂。最大行号是行的count(*)

with cte as (   
      select sl.*, 
             row_number() over (partition by product order by date desc) as rownumber,
             count(*) over (partition by product) as maxrn
      from saleslist sl
      where datediff( month, date, getdate() ) < 2 
    )
select product, 
     (
     (max(case when rownumber = 1 then price end) - 
         max(case when rownumber = maxn then price)
        )  /
         max(case when rownumber = maxn then price end)
       )
from cte
group by product;

答案 2 :(得分:0)

with cte as
(   
    select *, 
    row_number() over ( partition by product order by date desc ) as rownumber
    from saleslist
    where datediff( month, [date], getdate() ) < 2 
    )
select product, 
     (
     (max(case when rownumber = 1 then price end) - 
         max(case when rownumber = maxn then price end) --< missing end here 
        )  /
         max(case when rownumber = maxn then price end)
       )
from 
(select cte.*, max(rownumber) over (partition by product) as maxn 
   from cte ) t  --< needs an alias here
group by product