首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Server :错误MSG 102和MSG 156

Server :错误MSG 102和MSG 156
EN

Stack Overflow用户
提问于 2016-04-09 16:07:24
回答 3查看 215关注 0票数 0

请帮帮我。我写的查询

代码语言:javascript
复制
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)) /
          max(case when rownumber = maxn then price end)
       )
  from 
      (select cte.*, max(rownumber) over (partition by product) as maxn   
       from cte) 
group by product

我收到了以下信息

Msg 102,15级,状态1,13线 在“)”附近不正确的语法。 Msg 156,15级,状态1,18线 关键字“group”附近的语法不正确。

谁能告诉我怎么解决这个问题吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-04-09 16:14:20

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2016-04-09 16:23:47

server 2014支持第一个/最后一个值

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2016-04-09 16:11:48

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

代码语言:javascript
复制
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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36519298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档