sql server运行总计用,分区

时间:2014-05-03 11:00:40

标签: sql sql-server sql-server-2012

我正在尝试在以下查询中计算运行总计

select 
    a.ICode, MONTH(a.VDate), YEAR(a.vdate)
    , sum(isnull(a.qty, 0))
    , sum(isnull(a.qty, 0)) OVER (partition by a.icode order by a.icode) AS 'total' 
from 
    t_Stock as a
group by 
    a.ICode, MONTH(a.VDate), YEAR(a.vdate)
order by 
    a.icode, YEAR(a.vdate), MONTH(a.VDate)

但是我收到了一个错误:

  

Msg 8120,Level 16,State 1,Line 3
  专栏' t_Stock.Qty'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

为什么' t_Stock.Qty'需要在GROUP BY子句中,因为我已经在使用聚合函数(Sum(a.Qty))

一些演示数据:

icode   vtype   qty   vdate 
32114   Sales   -2    2013-06-03 18:09:17.953 
33459   Sales   -1    2013-06-03 19:39:59.843 
34446   Sales   -1    2013-06-03 20:46:17.030 
39914   Tra     -3    2014-01-07 13:02:31.000
30899   Sales   -1    2013-06-04 11:48:06.267 
25676   Sales   -3    2013-06-04 17:34:01.470 
32126   Sales   -1    2013-06-04 18:12:44.267 
34688   Sales   -1    2013-06-04 18:40:52.750 
31550   Sales   -1    2013-06-04 19:26:40.937 
32795   Sales   -1    2013-06-05 12:03:00.250 

3 个答案:

答案 0 :(得分:7)

使用带聚合的窗口函数时,实际上需要嵌套结果。以下是您的查询版本:

select a.ICode, MONTH(a.VDate), YEAR(a.vdate),
       sum(isnull(a.qty, 0)),
       sum(sum(isnull(a.qty, 0))) OVER (partition by a.icode order by a.icode) AS total
from t_Stock a
group by a.ICode, MONTH(a.VDate), YEAR(a.vdate)
order by a.icode, YEAR(a.vdate), MONTH(a.VDate);

我不确定你打算怎么做。让order by包含与partition by相同的值是不常见的。我希望这样的事情:

select a.ICode, MONTH(a.VDate), YEAR(a.vdate),
       sum(isnull(a.qty, 0)),
       sum(sum(isnull(a.qty, 0))) OVER (partition by a.icode
                                        order by year(a.vdate), month(a.vdate)
                                       ) AS total
from t_Stock a
group by a.ICode, MONTH(a.VDate), YEAR(a.vdate)
order by a.icode, YEAR(a.vdate), MONTH(a.VDate);

答案 1 :(得分:1)

写为:

select a.ICode,MONTH(a.VDate), YEAR(a.vdate)
, sum(isnull(a.qty,0)) OVER(partition by a.icode order by a.icode)
  AS 'Runningtotal'
, sum(isnull(a.qty,0)) OVER(partition by a.icode,MONTH(a.VDate), YEAR(a.vdate) 
  order by a.icode,YEAR(a.vdate),MONTH(a.VDate)) AS 'total' 
from 
t_Stock as a
--group by a.ICode ,MONTH(a.VDate), YEAR(a.vdate)
order by a.icode,YEAR(a.vdate),MONTH(a.VDate)

答案 2 :(得分:1)

为什么't_Stock.Qty'需要在GROUP BY子句中,因为我已经在使用聚合函数(Sum(a.Qty))?

出现这个问题是因为你使用“SUM(某物)”然后你使用“SUM(某物)”(分隔...)“

当你使用“SUM(某事物)”时,你需要“group by ...”条款 但是当你使用“SUM(某物)而过(分隔......)”时,它不接受/需要“group by ...”子句 http://technet.microsoft.com/en-us/library/ms189461.aspx

在他们之间选择一个。

如果您想同时使用它们,请尝试以下查询:

select a.ICode,MONTH(a.VDate) as 'month', YEAR(a.vdate) as 'year'
, bb.xtotal
,sum(isnull(a.qty,0)) OVER (partition by a.icode order by a.icode) AS 'total' 
from 
@temp a
inner join
(
 select b.ICode, b.vdate,
    sum(isnull(b.qty,0)) as xtotal
 from @temp b 
 group by b.Icode, b.vdate
) bb on a.Icode = bb.Icode and bb.vdate = a.vdate
order by a.icode,YEAR(a.vdate),MONTH(a.VDate)