2016-04-09 17 views
0

Lütfen bana yardım edin. Ben sorgu SQL Server: hata MSG 102 ve 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 

yazdım ve şu mesajları

Msg 102, Düzey 15, State 1

, Hat 13
yanlış sözdizimi yakın ')' aldık.

Msg 156, Düzey 15, Durum 1, Satır 18 'Grup' anahtar kelimesinin yakınında yanlış sözdizimi.

Birisi lütfen bunu nasıl düzeltebileceğimizi söyler misiniz?

+0

SQL Server sürümü nedir destekler? – dnoeth

cevap

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

Teşekkür ederim M.Ali !!!! Bunu takdir ediyorum! – Deepleeqe

0

Alt sorgu için bir tablo diğer adı gerekir. Ancak, sorgunuz aşırı karmaşık. Maksimum satır sayısı satır count(*) geçerli:

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

Teşekkür ederim Gordon !!! Bana gerçekten çok yardımcı oluyorsun !!! – Deepleeqe

1

SQL server 2014 İLK ​​/ 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

Bu harika! Teşekkür ederim dnoeth !! Bu kod çok kullanışlıdır! – Deepleeqe

İlgili konular