2016-04-09 15 views
0

私を助けてください。私は、クエリにSQL Server:エラーMSG 102とMSG 156

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 

を書いて、私は次のメッセージ

メッセージ102、レベル15、状態1、行13
近くに不正な構文を ')' です。

Msg 156、レベル15、状態1、行18
キーワード 'group'の近くに構文が正しくありません。

誰かがこれを修正する方法を親切に教えてください。

+0

SQL Serverのバージョンは何をサポートしていますか? – dnoeth

答えて

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

ありがとうM.Ali !!!!本当にそれを感謝します! – Deepleeqe

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

ありがとうございました!あなたは本当に私をたくさん助けます! – Deepleeqe

1

SQLサーバ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; 
+0

それは素晴らしいです!ありがとうdnoeth !!!!このコードは非常に便利です! – Deepleeqe

関連する問題