2015-06-02 92 views
2

我在這裏做錯了什麼? 結果是錯誤,說:試圖計算tsql中的累計和

消息102,級別15,狀態1,行3附近有語法錯誤順序'。

Msg 156,Level 15,State 1,Line 25關鍵字 'as'附近的語法不正確。


select * 
, Antal + Normtid as Flextid 
, SUM(antal) OVER (PARTITION BY transdate ORDER BY tekst) 
, x = row_number() over (partition by åruge order by tekst) 

from 
(
    select * 
    , 
    (
     select b.antal 
     from bi.dbo.Table_pg_FlextidsopgørelseGlUdgave b 
     where b.tekst = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.tekst 
     and b.transdate = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.transdate 
     and b.åruge = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.åruge 
     and b.type = 'Normtid' 
    ) as Normtid 

    from 
    bi.dbo.Table_pg_FlextidsopgørelseGlUdgave 
    where type = 'afholdt' 

    and tekst = 'fs' 
    --and åruge = '201501' 
) as data 
order by tekst, transdate 

問候

彼得

+1

select *僅在沒有其他選擇時才允許。請選擇表格*。 – jarlh

+1

也許第一個Select不知道列tekst。我寧願總是列出所有列,並且避免* – DangeMask

+1

是的,列出選擇列表中的所有列甚至更好! – jarlh

回答

0

你從派生表中獲取數據的方式是不正確的..

EX:

create table 
sales 
(
id int 
) 

insert into sales 
values 
(1), 
(2), 
(3) 

派生表應該總是表的別名和父表應該是指從

使用----這是有效的

select 
* from 
(
select id+1 as id1 
from sales 
) b 

- 這是無效

select 
* 
(select 
id from sales 
)b 

- -Aove有效當你有子查詢時說

select 
    id,(select t1.name from table t1 where t1.id=t2.id)as custname 
    from table t2 

來到你question..this不valid.I看到這兩個表類型相同

select * 
    , 
    (
     select b.antal 
     from bi.dbo.Table_pg_FlextidsopgørelseGlUdgave b 
     where b.tekst = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.tekst 
     and b.transdate = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.transdate 
     and b.åruge = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.åruge 
     and b.type = 'Normtid' 
    ) as Normtid 

    from 
    bi.dbo.Table_pg_FlextidsopgørelseGlUdgave 
    where type = 'afholdt' 

    and tekst = 'fs' 
    --and åruge = '201501' 

所以,你可以寫類似下面

select * 
, Antal + Normtid as Flextid 
, SUM(antal) OVER (PARTITION BY transdate ORDER BY tekst) 
, x = row_number() over (partition by åruge order by tekst) 

from 
(
    select * from 

    (
     select b.antal 
     from bi.dbo.Table_pg_FlextidsopgørelseGlUdgave b 
     where b.tekst = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.tekst 
     and b.transdate = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.transdate 
     and b.åruge = bi.dbo.Table_pg_FlextidsopgørelseGlUdgave.åruge 
     and b.type = 'Normtid' 
     and b.type='afholdt' 
     and b.tekst = 'fs' 

    ) as Normtid 

order by tekst, transdate 
+0

選擇*,(子查詢)作爲表中的子查詢在tsql中有效 –

+0

這在子查詢中是有效的,從問題中可以看出它不清楚他是否正在嘗試執行子查詢。我會將其添加到answer.thanks – TheGameiswar

2

很明顯,你有不恰當的版本Sql Server。累計總和與order by條款,如:

SUM(antal) OVER (PARTITION BY transdate ORDER BY tekst) 

只能從Sql Server 2012+。 其實我可以重現這些錯誤的Sql Server 2008

enter image description here

這是Sql Server 2012

enter image description here

注意如何錯誤消息的變化。