试图计算tsql中的累积和

时间:2015-06-02 12:43:49

标签: sql tsql

我在这里做错了什么? 结果是错误,说:

  

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

     

Msg 156,Level 15,State 1,Line 25关键字附近的语法不正确   '为'。

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

此致

彼得

2 个答案:

答案 0 :(得分: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

注意错误消息的更改方式。

答案 1 :(得分: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

- 如果您有子查询说

,则上述有效
   select 
    id,(select t1.name from table t1 where t1.id=t2.id)as custname
    from table t2

来到你的问题......这是无效的。我看到两种表格类型相同

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